0

I'm using this piece of code to make an ajax call:

 $('#filter').submit(function(){
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(), // form data
        type:filter.attr('method'), // POST
        beforeSend:function(xhr){
            filter.find('button').text('caricamento...'); // changing the button label
        },
        success:function(data){
            filter.find('button').text('Filtra'); // changing the button label back
            $('.load').html(data); // insert data
            $('.grve-iso-spinner').hide();
        }
    });
    return false;
});

I need to add more variables to the 'data' attribute, something like:

data : {
        var1: 'value1',
        var2 : 'value2'
    }

How can I merge the two data elements?

Thanks in advance

benedex82
  • 532
  • 2
  • 5
  • 18

4 Answers4

0

You can try this:

data: filter.serialize() + '&key=' + value,

It will add key: value pair to form serialize data. As serialize data is in the form of key: value pair, you can add additional values by following the same pattern

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
0

As jQuery serialize() function produces a text string in standard URL-encoded notation, you only have to concatenate the new values you want to add:

var data = filter.serialize();
data += "&var1=" + value1 + "&var2=" + value2;
Hulothe
  • 744
  • 1
  • 5
  • 17
0

Take a look at this answer: jQuery post() with serialize and extra data

It uses serializeArray and pushes the extra data to the array instead, you can then pass this array to the ajax call.

var data = $('#filter').serializeArray();
data.push({name: 'wordlist', value: wordlist});
Community
  • 1
  • 1
Christer
  • 1,651
  • 1
  • 17
  • 34
0

try this

var data = $('#filter').serializeArray();
data.push({name: 'var1', value: value1});
data.push({name: 'var2', value: value2});

$('#filter').submit(function(){
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:{ data : data }, // form data
        type:filter.attr('method'), // POST
        beforeSend:function(xhr){
            filter.find('button').text('caricamento...'); // changing the button label
        },
        success:function(data){
            filter.find('button').text('Filtra'); // changing the button label back
            $('.load').html(data); // insert data
            $('.grve-iso-spinner').hide();
        }
    });
    return false;
});
NewUser
  • 12,713
  • 39
  • 142
  • 236