I am using jQuery's $.ajax()
function to submit a form. I pass the form data like this:
data: form.serialize()
However, I would like to add additional data to the POST request.
According to this answer, the way to do this is to use serializeArray()
on the form, then push data onto the resulting array of objects. The problem is that when I then try to serialize the resulting array, jQuery returns an error.
Here is an example:
<form id="test">
<input type="hidden" name="firstName" value="John">
<input type="hidden" name="lastName" value="Doe">
</form>
JS:
console.log($("#test").serialize()); // firstName=John&lastName=Doe
var data = $("#test").serializeArray();
console.log(data); // [Object, Object]
data.push({name: 'middleName', value: 'Bob'});
console.log(data); // [Object, Object, Object]
console.log(data.serialize()); // Uncaught TypeError: undefined is not a function
JSFiddle
What am I doing wrong?
As pointed out by kapa, jQuery permits you to pass the array you get from serializeArray()
directly as a data
parameter, so your code can be as simple as;
var data = $("#test").serializeArray();
data.push({name: 'middleName', value: 'Bob'});
jQuery.ajax({
data: data,
// Other params
});
However, to explain why your previous code wasn't working (and here starts my previous answer); serializeArray()
literally returns an array. Array's don't have a serialize()
method on them; which is why your code was failing.
instead of using serialize()
on the array returned from serializeArray()
, call jQuery.param()
;
var data = $("#test").serializeArray();
data.push({name: 'middleName', value: 'Bob'});
console.log(jQuery.param(data));
jQuery.param()
is specifically provided to convert the { name, value }
pairs generated by serializeArray()
into a query string.
serialize
is a jquery method used to serialize a form object. Once you call serialize
, you no longer have a jquery object, and thus you cannot serialize it. You should be able to pass your JSON object to $.ajax
by stringifying it with the JSON object:
$.ajax({
data: JSON.stringify(data)
//...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With