75

I want to add extra data after i use $('#myForm').serialize() + extra data

$.ajax({
   type: 'POST',
   url: $('#myForm').attr('action'),
   data: $('#myForm').serialize(),   // I WANT TO ADD EXTRA DATA + SERIALIZE DATA
   success: function(data){
      alert(data);
      $('.tampil_vr').text(data);
   }
});
Toby Caulk
  • 266
  • 1
  • 6
  • 21
Joko Wandiro
  • 1,957
  • 1
  • 18
  • 28

3 Answers3

175

What kind of data?

data: $('#myForm').serialize() + "&moredata=" + morevalue

The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.

jthompson
  • 7,178
  • 2
  • 34
  • 33
  • thanks jthompson it works very well... I see $.ajax manual not serialize() ( newbie in ajax ) – Joko Wandiro Dec 10 '10 at 06:47
  • 9
    if more then a single data element nees to be added you can consider using `...serialize()+'&'+$.param(myParametersObject)` where myParametersObject is a simple object like `{'param':'val','param2':'val2',...}` – epeleg Jul 07 '13 at 19:40
  • 1
    `serialize` will url-encode the data, so I prefer to let it do the work: `$('#myForm, #moredataid').serialize()` – Andy G Sep 27 '19 at 08:23
12

Personally, I'd append the element to the form instead of hacking the serialized data, e.g.

moredata = 'your custom data here';

// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);

// append to the form
$('#myForm').append($input);

// then..
data: $('#myForm').serialize()

That way, you don't have to worry about ? or &

Bastien Jansen
  • 8,756
  • 2
  • 35
  • 53
steadweb
  • 15,364
  • 3
  • 33
  • 47
  • 1
    you're serializing a form so why would there ever be a case of ? or &??? It would always be a & unless you're serializing an empty form... `
    ` which in turn has no point
    – zgr024 Jul 16 '13 at 18:19
  • 1
    Why should I have to deal with that in the first place? Why not just append the element to the form, then serialize it, cleaner than having to concatenate strings to the serialized form, which the dev could get wrong simply by missing an & or = for each field added. – steadweb Jan 09 '14 at 23:22
  • 3
    Then I would recommend using `.serializeArray()` and appending the data to the array instead. It will post the same either way. See http://stackoverflow.com/questions/14102732/can-i-add-data-to-an-already-serialized-array – zgr024 Jan 10 '14 at 18:43
  • 2
    I agree. I just wouldn't want to append items to the serialized string, I'd rather have the jQuery do the hard work. – steadweb Jan 11 '14 at 19:12
4

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };
PrakashG
  • 1,642
  • 5
  • 20
  • 30