devjs11
devjs11

Reputation: 1958

Use and meaning of data: { get_param: 'value' } in jQuery ajax + JSON

I am parsing generated json with jquery $.ajax but there is one option that I dont understand. I saw it in some examples and tried to look for at jquery.com but still not sure about it:

this option is:

data: { get_param: 'value' }

which is used like this:

$.ajax({ 
                type: 'GET', 
                url: 'http://example/functions.php', 
                data: { get_param: 'value' }, //why we shell use that in that case?
                success: function (data) { 
                                    var names = data
                    $('#cand').html(data);
                }
          });

I know that "data:" is what sent to the server but parsing JSON I thought i don't send but retrieve from server with GET type. And the next part "get_param: 'value'" does not make sense to me in that case either, could anyone please explain when and what for and in what cases it shell be used?

thank you.

Upvotes: 0

Views: 3768

Answers (2)

Bergi
Bergi

Reputation: 665536

You don't send JSON (usually), you send simple GET or POST HTTP parameters. They are given to the ajax method in an object literal usually, but you could have used the string "getparam=value", too. If you provide an object, jQuery will do the parameter-serialisation and URL-encoding for you - they're sent as x-www-form-urlencoded.

To cite from the docs:

data (Object, String)

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.

Upvotes: 1

Quentin
Quentin

Reputation: 944500

I know that "data" is what sent to the server

Yes. If data is an object, it gets serialized to an application/x-www-form-urlencoded string and then placed in the query string or request body as appropriate for the request type (GET/POST).

jQuery does all the escaping necessary for this.

(It also, by default, collapses nested data structures (you don't have any in your example) into PHP-style by adding [] to key names).

but parsing JSON

JSON is not involved (unless the server responds with some).

when and what for and in what cases it shell be used

Whenever you want to pass data to the server rather than requesting a static URI.

Upvotes: 2

Related Questions