Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data to a form when submitting via a POST AJAX request? [duplicate]

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?

like image 491
Nate Avatar asked May 28 '14 12:05

Nate


2 Answers

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.

like image 140
2 revs Avatar answered Nov 01 '22 09:11

2 revs


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)
   //...
});
like image 1
Steve Danner Avatar answered Nov 01 '22 07:11

Steve Danner