152

I'm trying to find out if it's possible to post serialize() and other data that's outside the form.

Here's what I thought would work, but it only sends 'wordlist' and not the form data.

$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));

Does anyone have any ideas?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Vitaliy Isikov
  • 3,647
  • 9
  • 38
  • 46

9 Answers9

339

You can use serializeArray [docs] and add the additional data:

var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});

$.post("page.php", data);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 11
    Hmm. I think I like this better than my solution :) I may start doing this in the future. – Michael Mior Jul 08 '11 at 17:19
  • @Gudradain: It works just fine: http://jsfiddle.net/fnjncqhv/. If it doesn't work for you, you are facing a different problem. – Felix Kling Nov 19 '14 at 17:11
  • No it doesn't. http://jsfiddle.net/fnjncqhv/1/ serializeArray() produce an array of objects, each object containing a single property, if your data object contain more than 1 property (like in your example), it produces an invalid object and will not be bind on the server side. Please edit your answer to fix the problem. – Gudradain Nov 19 '14 at 18:36
  • 2
    @Gudradain: Please see my comment on your answer. You are wrong. `serializeArray` does not produce the structure you think it does. I'm not sure what you are trying to show with your demo. You are just alerting the length of the array. If my [**demo**](http://jsfiddle.net/akyz1Lcy/) doesn't convince you, please have a look at the [**documentation**](http://api.jquery.com/serializearray/). – Felix Kling Nov 19 '14 at 18:56
  • 1
    @FelixKling Sorry for that fail moment and thank you for the explanation. Didn't realize you really need the format {name: 'your-paramater-name', value : 'your-parameter-value'}, for every parameter that you want to add. – Gudradain Nov 19 '14 at 20:12
  • @Gudradain: No worries :) – Felix Kling Nov 19 '14 at 20:17
  • For some reason this not work. @Michael Mior has best solution. – Ivijan Stefan Stipić Feb 17 '15 at 21:28
56

Try $.param

$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
9

An alternative solution, in case you are needing to do this on an ajax file upload:

var data = new FormData( $('#form')[0] ).append( 'name' , value );

OR even simpler.

$('form').on('submit',function(e){

    e.preventDefault();
    var data = new FormData( this ).append('name', value );

    // ... your ajax code here ...

    return false;

});
r3wt
  • 4,642
  • 2
  • 33
  • 55
5

When you want to add a javascript object to the form data, you can use the following code

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        postData.push({name:key, value:data[key]});
    }
}
$.post(url, postData, function(){});

Or if you add the method serializeObject(), you can do the following

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
Community
  • 1
  • 1
Gudradain
  • 4,653
  • 2
  • 31
  • 40
  • 1
    This will basically generate an array that looks like `[{name: 'wordlist'}, {value: wordlist}]`. That's not in a format that jQuery understands, so I doubt this actually works. – Felix Kling Nov 19 '14 at 17:13
  • @FelixKling serializeArray() produce [{name1: 'value1'}, {name2: 'value2'}]. If you have an object data { name3 : 'value3', name4: 'value4' } and push it into the array from serializeArray(), you get [{name1: 'value1'}, {name2: 'value2'}, {name3:'value3', name4:'value4'}]. The last object in the array is invalid and you won't get result. – Gudradain Nov 19 '14 at 18:27
  • *"`serializeArray()` produce `[{name1: 'value1'}, {name2: 'value2'}]`."* No, it does not: http://jsfiddle.net/akyz1Lcy/ – Felix Kling Nov 19 '14 at 18:55
5

In new version of jquery, could done it via following steps:

  • get param array via serializeArray()
  • call push() or similar methods to add additional params to the array,
  • call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.

Example code:

var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
    // ...
}
Eric
  • 22,183
  • 20
  • 145
  • 196
3
$.ajax({    
    type: 'POST',  
    url: 'test.php',  
    data:$("#Test-form").serialize(),  
    dataType:'json',
     beforeSend:function(xhr, settings){
     settings.data += '&moreinfo=MoreData';
     },
    success:function(data){
            //  json response  
    },
    error: function(data) { 
        // if error occured
    }
    });
2

You can use this

var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
Jako
  • 944
  • 14
  • 33
Marouane B.
  • 151
  • 7
1

You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.

Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:

var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);
Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

I like to keep objects as objects and not do any crazy type-shifting. Here's my way

var post_vars = $('#my-form').serializeArray();
$.ajax({
  url: '//site.com/script.php',
  method: 'POST',
  data: post_vars,
  complete: function() {
    $.ajax({
      url: '//site.com/script2.php',
      method: 'POST',
      data: post_vars.concat({
        name: 'EXTRA_VAR',
        value: 'WOW THIS WORKS!'
      })
    });
  }
});

if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!

Hope this helps.

Mathlight
  • 6,436
  • 17
  • 62
  • 107
A A Karim
  • 123
  • 1
  • 6