How do I POST an array of objects with $.ajax (jQuery or Zepto)

174,517

Solution 1

Be sure to stringify before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.

Works:

$.ajax({
    url: _saveAllDevicesUrl
,   type: 'POST'
,   contentType: 'application/json'
,   data: JSON.stringify(postData) //stringify is important
,   success: _madeSave.bind(this)
});

I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.

Solution 2

Try the following:

$.ajax({
  url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});

Solution 3

edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).

As simple as:

JSON.stringify(yourData)

You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:

$.post(_saveDeviceUrl, {
    data : $.toJSON(postData)
}, function(response){
    //Process your response here
}
);

Solution 4

Check this example of post the array of different types

function PostArray() {
    var myObj = [
        { 'fstName': 'name 1', 'lastName': 'last name 1', 'age': 32 }
      , { 'fstName': 'name 2', 'lastName': 'last name 1', 'age': 33 }
    ];

    var postData = JSON.stringify({ lst: myObj });
    console.log(postData);

    $.ajax({
        type: "POST",
        url: urlWebMethods + "/getNames",
        data: postData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            alert(response.d);
        },
        failure: function (msg) {
            alert(msg.d);
        }
    });
}

If using a WebMethod in C# you can retrieve the data like this

[WebMethod]
    public static string getNames(IEnumerable<object> lst)
    {
        string names = "";
        try
        {
            foreach (object item in lst)
            {
                Type myType = item.GetType();
                IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

                foreach (PropertyInfo prop in props)
                {
                    if(prop.Name == "Values")
                    {
                        Dictionary<string, object> dic = item as Dictionary<string, object>;
                        names += dic["fstName"];
                    }
                }
            }
        }
        catch (Exception ex)
        {
             names = "-1";
        }
        return names;
    }

Example in POST an array of objects with $.ajax to C# WebMethod

Share:
174,517
SimplGy
Author by

SimplGy

JS Dev. Simple-to-use software. SOreadytohelp

Updated on July 09, 2022

Comments

  • SimplGy
    SimplGy almost 2 years

    I'd like to POST an array of objects with $.ajax in Zepto or Jquery. Both exhibit the same odd error, but I can't find what I'm doing wrong.

    The data saves to the server when sent using a test client like 'RestEasy', and I can see the request getting mangled in the browser's net panel, so I believe JS is the culprit.

    If I send an array of objects as the data property of a POST, they are not properly sent.

    Data object:

    var postData = [
        { "id":"1", "name":"bob"}
      , { "id":"2", "name":"jonas"}
      ]
    

    Request:

    $.ajax({
      url: _saveDeviceUrl
    , type: 'POST'
    , contentType: 'application/json'
    , dataType: 'json'
    , data: postData
    , success: _madeSave.bind(this)
    //, processData: false //Doesn't help
    });
    

    Request body as seen in the browser:

    "bob=undefined&jonas=undefined"
    

    This can be seen more directly by using the $.param method that both jQuery and Zepto use to prepare POST data.

    $.param(
      [
        { "id":"1", "name":"bob"}
      , { "id":"2", "name":"jonas"}
      ]
    )
    // Output: "bob=undefined&jonas=undefined"
    

    So it seems like the preparation that these libraries do for complex post data is different than I expect.

    I see this answer, but I don't want to send the data as a query param as I'm POSTing lots of content. How do I send an array in an .ajax post using jQuery?

    What is the correct way to send multiple objects over POST using jQuery/Zepto?

    Using $.ajax({... data: JSON.stringify(postData) ...}) sends non-mangled content, but the server doesn't like the format.

    Update: Seems like JSON.stringify sends correctly formatted content. The issue is that the server side is very, very specific about the structure of the object that it wants. If I add or remove any properties from the object, it will fail the whole process rather than using the properties that do match. This is inconvenient because it's nice to use server-sent content as a view model, but view models get changed. ...Still working on the best solution.

  • SimplGy
    SimplGy almost 12 years
    It's already a javascript object, I thought the conversion was trivial or automatically handled by these libraries. What conversion is it actually doing between js object and JSON transfer object? Is this the same as JSON.stringify?
  • shanehoban
    shanehoban almost 10 years
    Hey there, just a quick one. I've build a parameter list as a string in URL format via a few += statements, e.g. x=123&y=1234&z=12345 ... now it is quite long to be honest... very long. I know the URL too, so can I theoretically just do data: myParamString, or do I need to JSON.stringify it too? Thanks, I know this is an old question
  • SimplGy
    SimplGy over 9 years
    @shanehoban in a POST, the parameters are typically sent in the body, not as URL params. Are you doing a GET? In any case, I don't think this is very related. Might want to open a different question.
  • shanehoban
    shanehoban over 9 years
    Thanks, I understand now - this was a while ago :) @Simple much appreciated though!
  • Vinicius Lima
    Vinicius Lima almost 8 years
    That's a better approach since an Array in javascript by itself is not a JSON. Even { [] } is not valid. The array needs to be wrapped by an Object and inside a property.
  • Damien JALLON
    Damien JALLON almost 8 years
    Thanks, the best solution is yours. It has helped me sending an array of object with ajax to my web ASP.net api.
  • Andrew
    Andrew about 7 years
    How about tell us what data is in postData so we know what this answer actually solved. And importantly, what data you tried to use that it did not work with. Currently all these answers are incomplete.