2

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!

baikho
  • 5,203
  • 4
  • 40
  • 47
Syamsoul Azrien
  • 2,534
  • 4
  • 32
  • 55

4 Answers4

2

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.

Community
  • 1
  • 1
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
2

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).

dipdipdip
  • 2,326
  • 1
  • 21
  • 31
1

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

Simus
  • 126
  • 3
1

As already mentioned above AJAX stands for Asynchronous JavaScript and XML. To make an httpRequest in Java Android i strongly suggest Volley Library and Singleton Pattern: https://developer.android.com/training/volley/request