I am wondering how to call a function just like in jQuery, but then in Java (for a native Android app).
$.ajax({
url:"http://test.com/read_mySQL.php",
method:"POST",
data:{username:uname_field,password:upass_field},
}).success(function(response){
if (response=="correct"){
alert("You are now logged in");
}
});
Above is the code for JavaScript, but I am wondering what the code would look like in Java.
Thank you!
With Android you can use OkHttp
An example from there
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Update
Plase, read this article Using OkHttp, espessially Asynchronous Network Calls. Because of you will need to do requests asynchronously.
Refer "Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?" for some additional notes about why preferable to using OkHttp
over AsyncTask.
AJAX - Asynchronous JavaScript and XML
As the name stated ajax belongs to JavaScript. You should use a native android library to make your requests.
I suggest to use OkHttp (Http Client) in combination with Retrofit 2 (allows easy asynchronous calls like ajax and much more).
As what I studied, AsyncTask is for calling another thread (Background running), so, is it are used for AJAX also?
No. But any HTTP calls in new Android versions (4.x) are required to be called in AsyncTask.
And also, you need android.INTERNET permission.
Otherwise, it wouldn't work.
For more info, you can read this:
Simply Android GET & POST Requests Examples
http://codeproject.com/Tips/1034468/Android-Simply-Sending-HTTP-GET-POST-Requests-To-S