0

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.

Rami Alshareef
  • 6,787
  • 11
  • 44
  • 74
mrdaliri
  • 6,816
  • 22
  • 70
  • 102
  • 1
    see this question: [serializing to json](http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery) – Vlad Balmos Sep 29 '11 at 08:58
  • for cross browser support add this javascript file in your html: [https://github.com/douglascrockford/JSON-js/blob/master/json2.js](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) it should provide JSON.stringify – Shlomi Komemi Sep 29 '11 at 09:03
  • You can also make it work in IE by including a java script from here: http://www.json.org/js.html It is a commonly used approach. – mateusz.fiolka Sep 29 '11 at 08:54
  • Include this js file [JSON.js](https://github.com/douglascrockford/JSON-js) Then you will get the JSON.stringify() method. – dhinesh Sep 29 '11 at 08:56

2 Answers2

1

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.

GregL
  • 34,883
  • 8
  • 60
  • 65
0

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 );
   }
 });
ipr101
  • 23,772
  • 7
  • 57
  • 61