mark smith
mark smith

Reputation: 20907

Passing js object as json to jquery?

I have the following but it's not working, I read somewhere on the stackoverflow that it works like this but I can't seem to get it to work.. it errors... am I doing something wrong?

If I do pass data like this - it works -- so I know my service is working

//THIS WORKS
data: "{one : 'test',two: 'test2' }"


// BUT SETTING UP OBJECT doesn't work..

var saveData = {};
saveData.one = "test";
saveData.two = "tes2";


$.ajax({
    type: "POST",
    url: "MyService.aspx/GetDate",
    data: saveData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert(msg.d);
    },
    error: function(msg) {
    alert('error');
    }

});

Upvotes: 13

Views: 39919

Answers (3)

Lance McNearney
Lance McNearney

Reputation: 9490

My suggestion would be to use the jquery-json plug-in and then you can just do this in your code:

...
data: $.toJSON(saveData),
...

Upvotes: 3

Matt Winckler
Matt Winckler

Reputation: 2233

According to this blog post, the reason it doesn't work when you try to pass the object is that jQuery attempts to serialize it. From the post:

Instead of passing that JSON object through to the web service, jQuery will automatically serialize and send it as:

fname=dave&lname=ward

To which, the server will respond with:

Invalid JSON primitive: fname.

This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter[...]

Which is what you're doing in the example that works.

Upvotes: 4

Tim Hoolihan
Tim Hoolihan

Reputation: 12396

I believe that code is going to call .value or .toString() on your object and then pass over the wire. You want to pass JSON.

So, include the json javascript library

http://www.json.org/js.html

And then pass...

    var saveData = {};
    saveData.one = "test";
    saveData.two = "tes2";


    $.ajax({
        type: "POST",
        url: "MyService.aspx/GetDate",
        data: JSON.stringify(saveData),      // NOTE CHANGE HERE
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            alert(msg.d);
        },
        error: function(msg) {
        alert('error');
        }

    });

Upvotes: 30

Related Questions