Neshta Neshta - 6 months ago 61
Javascript Question

Result of Array.map is undefined in Ajax request

I have very confusing behaviour in javascript. The body of HTTP request is

undefined=&undefined=
.

var data = [1, 2].map(function(item) {
return {
Id: item,
Quantity: 1
}
});

$.ajax({
url: "someUrl",
type: "POST",
dataType: "json",
data: data
});


How can I prevent from losing data? Please advise.

Answer

The problem is that you are posting data with Content-Type:application/x-www-form-urlencoded header. Check documentation for $.ajax. In this case data passed will be serialized with $.param method, which if you check documentation does the following:

Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.

And now you know why the data is posted as

undefined=undefined&undefined=undefined

Finally, if you want to post a JSON payload you can stringify data yourself and add application/json content-type:

$.ajax({
    url: "someUrl",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8"
});
Comments