views:

57

answers:

4

Hello all,

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

+1  A: 

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.

Andy E
If your input field is in a form, just use form.serialize() to easily get the data parameter.
Tim
@Tim: you can, but the OP specifically said he wants to encode the POST data in JSON format. *serialize()* doesn't do JSON encoding.
Andy E
And why will we what to use: 'data='+encodeURIComponent(myJSON) instead of '$('#myInputField').val();' ?
MEM
True Andy. But I'm a little bit lost. I've hear, here and there, that json is a nice thing... I'm not yet sure, when to use it. :s
MEM
Nick Craver
@MEM: Nick pretty much said it all here. You don't need to use JSON if you're sending a simple value. It's very useful to return JSON from the server, but it's rare to send the data in that format.
Andy E
So, that is a json format on the second argument right? Please have patience with me. I'm almost getting it:SO, Why do we use: {data: $('myInputField').val() } and not just $('myInputField').val() ?
MEM
@MEM: query strings should be in name=value pairs. Providing `$('myInputField').val()` on its own would be just handing a name to PHP. Moreover, this name would be dynamic, changing for each request. Using `{ data: $('myInputField').val() }` assigns the value to the *data* param so we can access it server side with `$_POST['data']`.
Andy E
I thought that query strings were only something that we could use with $_GET method. Big mess... Need to read more about them. Still:You both stated that "I don't need to use JSON for sending a simple value" - but it seems that we are using if we do: { data: $('#myInputField').val() } , or this just happens to be the same sintax?Don't abandoned me... I'm sure others may found this dialogue useful. :D
MEM
This is related and with this, this answers gets almost complete. http://stackoverflow.com/questions/3547196/jquery-doubt-about-jquery-post-second-argument-json-or-query-stringThe only thing missing here is: what kind of thing is this query-string. Is it related with the query strings that we know that are passed on the URL using the get method, or is this totally different?
MEM
@MEM: `{ data: $(...) }` isn't quite the same thing as JSON. In JavaScript, {} represents an object literal. JSON is a data transportation format, it is a string by nature - a string representation of a JavaScript object literal with certain limitations to increase security. In the *$.post()* method jQuery converts an object literal to a query string, in name/value pairs.
Andy E
@Andy E - Ok. And that query string is "something" that we send using POST or GET ?
MEM
@MEM: yes. A GET query string is visible in the address bar of the browser, a POST query string isn't.
Andy E
Andy E, as a newbie, I want to be better formed: (I should start a newbie movement) :)Here:http://en.wikipedia.org/wiki/Query_stringWe can read:"In World Wide Web, a query string is the part of a Uniform Resource Locator (URL) that contains data to be passed to web applications such as CGI programs."So, it's not correct. Since we can ALSO have a query string using POST, hence, nothing to do with URL send. OR, by using POST we are also sending a URL ?Almost... :D
MEM
@MEM: I probably shouldn't have used the term query string as it is a term more associated with URLs. In a POST request, "request body" is a more accurate term, although with form data, the format is the same as that of a URL's query string.
Andy E
Perfect. Thanks for the clarification. :)
MEM
A: 

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.

jpluijmers
A: 

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); } );
pholz
"If you return a JSON structure, you can then access replyData.foo" PRECIOUS! I was having that doubt as well. Thanks a lot!
MEM
A: 

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.

Oleg