¿Cómo agregar datos a un formulario cuando se envía a través de una solicitud POST AJAX? [duplicar]

Estoy usando 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.

Según esta respuesta, 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.

Aquí hay un ejemplo:

<form id="test">
    <input type="hidden" name="firstName" value="John">
    <input type="hidden" name="lastName" value="Doe">


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 


¿Qué estoy haciendo mal?

preguntado el 28 de mayo de 14 a las 13:05

Why are you trying to call serialize on it? Simply follow the example code in the linked answer. Use data in your AJAX call, it is ready. Like data: data. -

Did you try to use data in your ajax call after .push(); you shouldn't try to serialize the array. -

@kapa the examples I've found for $.ajax() show the data as being passed as form.serialize(), which puts the inputs into a string (like a GET request would). That's why I'm trying to call serialize() on the array, to convert it to a string. -

You may also use JSON jsfiddle.net/hqj4E/1 -

@Nate Just read the docs instead of following examples blindly. Or follow examples blindly, and simply copy it from the answer in the linked question. Both methods will work in this case :). -

3 Respuestas

As pointed out by kapa, jQuery permits you to pass the array you get from serializeArray() directamente como un data parameter, so your code can be as simple as;

var data = $("#test").serializeArray();

data.push({name: 'middleName', value: 'Bob'});

    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.

En lugar de usar serialize() on the array returned from serializeArray(), llamada jQuery.param();

var data = $("#test").serializeArray();

data.push({name: 'middleName', value: 'Bob'});

jQuery.param() is specifically provided to convert the { name, value } pairs generated by serializeArray() into a query string.

contestado el 28 de mayo de 14 a las 13:05

It is unnecessary AFAIK. jQuery will be able to work with data simplemente. - Kapa

@kapa: Ahhh you're right. I didn't realise jQuery supported that. I'll update my answer! - Matt

Gracias por informarme sobre jQuery.param(...). I have to start using it. - afaolek

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:

   data: JSON.stringify(data)

contestado el 28 de mayo de 14 a las 13:05

-1 Why would you transform it to JSON? What is a JSON object in your language? :) - Kapa

This will not give you the same POST data as normal serialization. - Matt

In addition to the other answer, sometimes it is easier to simply add hidden input elements, before the serilazation.

$('<input type=hidden>').attr({name:'middleName',value:'bob'}).appendTo('form#test')

contestado el 28 de mayo de 14 a las 13:05

This should be a comment and not an answer since it doesn't answer the question. - afaolek

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.