mrdaliri
mrdaliri

Reputation: 7328

convert objects to JSON and send via jquery ajax

I've 1 object:

var myobject = {first: 1, second: {test: 90}, third: [10, 20]};

and I want to send it as JSON string via jQuery ajax.

How can I do it? (i test JSON.stringify(), but it doesn't work in IE)

Thanks.

Upvotes: 0

Views: 3226

Answers (2)

GregL
GregL

Reputation: 38103

If you specify your myobject as the data parameter to the jQuery .ajax() method, it will automatically convert it to a query string, which I believe is what you want.

e.g.

$.ajax({
    url: /* ... */,
    data: myobject,
    /* other settings/callbacks */
})

From the docs:

data

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.

Upvotes: 1

ipr101
ipr101

Reputation: 24236

You should be able to pass your object to the 'data' parameter of the ajax function -

$.ajax({
   type: "POST",
   url: "some.php",
   data: myobject ,
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

Upvotes: 0

Related Questions