jquery $.post - json - proper way to send/receive input data (on the client side only) - A Two Questions Quest

StackOverflow https://stackoverflow.com/questions/3546661

  •  30-09-2019
  •  | 
  •  

Question

Let's imagine that we have something like:

$.post('somescript.php', 'WHAT CAN WE PUT HERE?',
        function(replyData) {

1) By default, the third argument of $.POST method, will read the XMLResponse response correct? So, why do we need that argument 'replyData' ? What are the reasons that we may have for having that argument?

2) The second argument accepts the data that will be sent. Ok. I would like to use json, however, I'm not sure if I should use a json format on that second argument or target the input form field that will contain that data?

Additional notes: The data will come from a input field, and I need to send it via an $.POST ajax request to the server. I intend to use json encode and json decode php functions.

Thanks in advance, MEM

Was it helpful?

Solution

The replyData argument contains the body of the response returned by the server, which you can then manipulate to display on your page, verify that the server-side processed the data successfully, etc. You don't have to use it (for example, if you don't return any data).

The data that you're supplying (in JSON format), will still need to be in the form of a query string, e.g. param=value. The value will also need properly encoding, using encodeURIComponent():

$.post('somescript.php', 'data='+encodeURIComponent(myJSON),
    function(replyData) {

Then, you can access the JSON in the PHP script through the $_POST superglobal:

$data = json_decode($_POST['data']);

JSON would be a little overkill for a simple input field, however. It's uncommon to use JSON in place of name/value pairs for form fields.

OTHER TIPS

1) The third argument is the callback function. If you supply an anonymous function, as in your sample, you need to name the argument to access it. If you return a JSON structure, you can then access replyData.foo etc.

2) You can pull the values from your form and construct a JSON structure.

var data = {};
data.threadid = $(form).find('input[name=threadid]').val();
data.commentid = $(form).find('input[name=commentid]').val();

$.post('somescript.php', data, function(replyData) { alert(replyData.foo); } );

I stole this function from Drupal and fixed the trailing comma on arrays and objects wich caused Zend_Json_Server to throw exceptions.

    var toJson = function(v) {
  // typeof null == object so we check beforehand;
  if ( v == null ){
    return null;  
  }

  switch (typeof v) {
    case 'boolean':
      return v == true ? 'TRUE' : 'FALSE';
    case 'number':
      return v;
    case 'string':
      return '"'+ v +'"';
    case 'object':
      if ( !(v instanceof Array) ){
          var output = "{";
          for(i in v) {
            output = output + '"'+i+'"' + ":" + toJson(v[i]) + ",";
          }
          output = output.substr(0,output.length-1) + "}"; // Fix the trailing comma error wich isn't officialy allowed.
      }else{
          var output = "[";
          for(i in v) {
            output = output + toJson(v[i]) + ",";
          }
          output = output.substr(0,output.length-1) + "]"; // Fix the trailing comma error wich isn't officialy allowed.
      }
      return output;
    default:
      return null;
  }
}

Now just feed it your data like this:

var myJsonString = toJson($('myform').serialize());

Wich will return a json string recursively generated from your variable. Works for most of my applications.

In general I agree with Andy E that if you look at the string of data which will be posted they should looks like

'data='+encodeURIComponent(myJSON)

I want only to clear, that in the practice one use the second parameter of $.post mostly not as a string:

$.post('somescript.php', 'data='+encodeURIComponent(myJSON), ... );

but as a object:

$.post('somescript.php', {data: myJSON}, ...);

Then jQuery call encodeURIComponent function and construct the string 'data='+encodeURIComponent(myJSON) with respect of jQuery.param() internally. Much more important to understand, that to have myJSON you have to produce this JSON string with respect of some JSON encoding functions from an object which contains the data which you want to post. So the code will looks in the practice like following

$.post('somescript.php', { data: JSON.stringify(myObject) }, ...);

where JSON.stringify is a JavaScript function from json2.js which you can free download from http://www.json.org/js.html.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top