I am trying to figure out how to append two more values to the serialize method in JQuery. I have the following code to submit a form with ajax and have two more variables that I would like to append:
Thank you!
... var formData = $('#contact_form').serialize(); submitForm(formData); // ----------------------------------------------- // AJAX FORM SUBMIT // ----------------------------------------------- function submitForm(formData){ $.ajax({ type: 'POST', url: 'contact.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { // display success message response(data.msg,'show'); }, error: function(XMLHttpRequest, textStatus, errorThrown) { ... }, complete: function(XMLHttpRequest, status) { ... } }); }
jQuery serialize() Method The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .
You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.
If you change serialize()
to serializeArray()
you can push values into the array :
var formData = $('#contact_form').serializeArray(); formData.push({ name: "<something>", value: "<somevalue>" }); submitForm(formData);
The data can still be sent in the same way as you would with the serialize()
method, using the $.ajax()
method
You can add new values by appending to your variable:
formData += '&var1=blah&var2=blah';
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