0

I want to POST a data object that contains an array.

I believe the object needs to be serialized before it is posted but I don't know how to do that.

I tried the below but the serialize function I'm using breaks because my object contains an array :

var serialize = function (obj, prefix) 
{
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
};

$.ajax({
  type: 'POST',
  url: '/xxxx',
  data: serialize({
    a: 'xxx',
    b: 123456,
    c: [{d: "xxx", e: "xxx"}, {d: "xxx", e: "xxx"}]
  })
});

});

1
  • To add to the answer under, jQuery already have a serialize() function for Form Elements. Commented Sep 13, 2015 at 17:14

2 Answers 2

1

In AJAX data could be PlainObject/String/Array

data

Type: PlainObject or String or Array

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. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

$.ajax({
  type: 'POST',
  url: '/xxxx',
  data: {
    a: 'xxx',
    b: 123456,
    c: [{
      d: "xxx",
      e: "xxx"
    }, {
      d: "xxx",
      e: "xxx"
    }]
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

It depends entirely on how you want to serialise it. There is no standard for expressing an array in any of the standard data types that a form would support.

If you just pass the plain object to jQuery's data then it will serialise it as www-url-form-encoded using PHP's conventions for representing arrays (which you can then access via $_POST in PHP or with this Perl module).

If you pass it through JSON.stringify() then you'll get JSON (and should also specify contentType: "application/json").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.