Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 651
MEM Avatar asked Aug 23 '10 10:08

MEM


1 Answers

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.

like image 94
Andy E Avatar answered Sep 25 '22 21:09

Andy E