Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Appending to Serialize

Tags:

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) {                  ...             }         });     } 
like image 245
user1002039 Avatar asked Nov 27 '11 21:11

user1002039


People also ask

What is serialize () in jquery?

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.

How do you serialize data in JavaScript?

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() .

What will you use in jquery if you wanted to convert the contents of a form elements into string for submission?

You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.


2 Answers

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

like image 75
Manse Avatar answered Oct 11 '22 18:10

Manse


You can add new values by appending to your variable:

formData += '&var1=blah&var2=blah'; 
like image 44
Sal Avatar answered Oct 11 '22 17:10

Sal