Passing additional variables to ajax with serialize() in JQuery

If you use JQuery and needs to pass a number of variables to a new page by ajax, you are probably familiar with the function serialize(), which gets all inputs in your form and send them to the desired url.

In this post, I will show you how you can add other variables to the data you are sending with serialize.

The snippet below would be my normal approach when using  ajax and serialize:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<script>
$(function() {
    $('#frm').on('submit', function(e){
        if (e.isDefaultPrevented()) return;
        e.preventDefault();
        $.ajax({
            type:"POST",
            url:"/newpage.php",
            data:  $("#frm").serialize(),
            success: function(response){ 
                alert(response);
                break;
                }
        });         
    });
});
</script>

If I need to insert other variables, I would then use serializeArray() instead of serialize, pushing other variables as needed:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<script>
$(function() {
    $('#frm').on('submit', function(e){
        if (e.isDefaultPrevented()) return;
        e.preventDefault();
        var parameters = $("#frm").serializeArray();
        parameters.push({name: 'newvar', value: 'newvalue'}); //insert here what you need       
        $.ajax({
            type:"POST",
            url:"/newpage.php",
            data:  parameters,
            success: function(response){ 
                alert(response);
                break;
                }
        });         
    });
});
</script>