$(this).serialize() -- How to add a value?

TheExit picture TheExit · Jun 30, 2011 · Viewed 107.1k times · Source

currently I have the following:

$.ajax({
    type: 'POST',
    url: this.action,
    data: $(this).serialize(),
});

This works fine, however I would like to add a value to data, so I tried

$.ajax({
    type: 'POST',
    url: this.action,
    data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
});

But that didn't post correctly. Any ideas on how you can add an item to the serialize string? This is a global page variable that isn't form specific.

Answer

Leigh Brenecki picture Leigh Brenecki · Jul 23, 2013

While matt b's answer will work, you can also use .serializeArray() to get an array from the form data, modify it, and use jQuery.param() to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});