28

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) { 
                ...
            }
        });
    }
user1002039
  • 860
  • 4
  • 17
  • 31

2 Answers2

54

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

Barilee
  • 57
  • 6
Manse
  • 37,765
  • 10
  • 83
  • 108
  • I've modified it like this but firebug tells me that push is not a function: var formData = $('#contact_form').serializeArray(); formData.push({name:"cat", value: selectedCat}).serialize(); formData.push({name:"subcat", value: selectedSubCat}).serialize(); submitForm(formData); – user1002039 Nov 27 '11 at 22:03
  • @user1002039 works fine for me : http://jsfiddle.net/manseuk/BHXxx/ do your form inputs have `name` attributes ? – Manse Nov 27 '11 at 22:14
  • My form inputs are working fine. I need to append the values of two extra variables to the serialize method. – user1002039 Nov 27 '11 at 22:29
  • 1
    Seems not to work if the from data is stored in Form Input Arrays. – Valentin Despa Oct 18 '13 at 14:32
  • @Falcon is right, his link works (see second answer from top). This doesn't work for me, sadly I can't downvote anymore. – Deproblemify Feb 11 '14 at 12:06
18

You can add new values by appending to your variable:

formData += '&var1=blah&var2=blah';
Sal
  • 1,657
  • 12
  • 9