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
What am I doing wrong?