0

I am new t ajax, but quite familiar with android. I am converting a ajax program to android app. As a part of it, i need to post data to the server. Below is the given post command in ajax.

var postTo = 'xyz.php';
 $.post(postTo,{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' } ,
 function(data) {

 if(data.success){
 window.localStorage["sa_id"] = data.mid;
 window.location="getempdb.html";
 }

 if(data.message) {
 $('#output').html(data.message);
 } else {
 $('#output').html('Could not connect');
 }
 },'json');

I want to implement this in android but under very little from the above statements. Could anyone who is good at ajax help me out with this thing. As of now, i get the user name and telephone number as a edit text input. I need to send this to php using http client. I know how to send data using php, but do not know what format to send and whether its a string to send or as a json object to send. Please help in interpreting the above code and oblige.

bharath
  • 953
  • 4
  • 17
  • 30

1 Answers1

1

Apparently, this uses UrlEncodedFormEntity if you are using HttpClient in android.

This is created by using a List of NameValuePair.

from the parameters to the $.post:

{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' }

You have to create a NameValuePair for employee_name, one for phone ... each of which is fetched from a HTML element name employee_name, phone ... This is where you put the values from your EditTexts.

It returns a JSON formatted String, which you have to parse (typically using JSONObject obj = new JSONObject(result); once you have fetched the result from the server)

In this JSON object, you have a key named success, which format is not specified, except you can assume things went well if it is present ; a key mid, and a key message.

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • Thanks for the wonderful explaination. But this is a httppost, so effectively, i have to create a json object with fields of employee_name and phone as its key value pairs and need to post them with content type = application/json, am i correct? – bharath Apr 25 '13 at 13:05
  • i don't think the post body is expected to be a json object. I think it is simply a UrlEncodedFormEntity, so you'll call httppost.setEntity(myUrlEncodedFormEntity); with your namevaluepairs in the entity, rather than a StringEntity with a json content. – njzk2 Apr 25 '13 at 13:46