Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
    }

});
like image 586
mark smith Avatar asked Jun 01 '09 21:06

mark smith


People also ask

How do I pass a JSON object?

Send JSON Data from the Client SideUse JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.

Can you JSON parse an object?

JSON. parse() is a crucial method for converting JSON data in string form into Javascript objects. It is possible to convert simple or complex objects, but you should never convert calculations or code, like for loops.

How do you pass a JSON object as a parameter in Java?

Either use an export mapping to create a JSON string that you can pass to the Java action and then create a JSON object again from that string or just pass a root object to the Java and then in Java retrieve all the attached objects over the references to that root object.


1 Answers

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');
        }

    });
like image 66
Tim Hoolihan Avatar answered Oct 21 '22 13:10

Tim Hoolihan