148

Is it possible to send form elements (serialized with .serialize() method) and other parameters with a single AJAX request?

Example:

$.ajax({
    type : 'POST',
    url : 'url',
    data : {
        $('#form').serialize(),
        par1 : 1,
        par2 : '2',
        par3: 232
    }
}

If not what's the best way to submit a form together with other parameters?

Thanks

informatik01
  • 16,038
  • 10
  • 74
  • 104
KenavR
  • 3,769
  • 9
  • 37
  • 47

13 Answers13

276

serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
88

Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

var data = form.serialize() + '&' + $.param(object)

See http://api.jquery.com/jQuery.param for further reference.

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
kliszaq
  • 1,086
  • 8
  • 9
  • 11
    I like this one. It means I don't have to look at an ugly querystring! – Greg Woods Apr 19 '13 at 14:29
  • 4
    This is the better way, by far. The accepted answer is messy and should never be used in any production application. – FastTrack Apr 05 '16 at 20:22
  • 4
    If we're talking about a production environment, then none of these answers should be used. The `form` should contain all information (in hidden fields if necessary) so that it can be serialised in a single call. This way if JS is disabled or fails, the form submission should still have a failsafe and include all data when sent. – Rory McCrossan Oct 15 '16 at 12:12
11

I dont know but none of the above worked for me, Then i used this and it worked :

In form's serialized array it is stored as key value pair

We pushed the new value or values here in form variable and then we can pass this variable directly now.

var form = $('form.sigPad').serializeArray();
var uniquekey = {
      name: "uniquekey",
      value: $('#UniqueKey').val()
};
form.push(uniquekey);
Rohit Arora
  • 2,246
  • 2
  • 24
  • 40
5

If you want to send data with form serialize you may try this

var form= $("#formId");
$.ajax({
    type: form.attr('method'),
    url: form.attr('action'),
    data: form.serialize()+"&variable="+otherData,
    success: function (data) {
    var result=data;
    $('#result').attr("value",result);

    }
});
4302836
  • 387
  • 1
  • 6
  • 14
2
$("#add_form").submit(function(e) {
    e.preventDefault();
    var total_qty = $('#total_qty').text();
    var total_amt = $('#total_amt').text();
       
    $("#add_btn").val('adding....');
    $.ajax({
        url: 'action.php',
        method: 'post',
        data: $(this).serialize() + "&total_qty="+total_qty + "&total_amt="+total_amt,
        success: function(data){
            console.log(data);
        }   
    });
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
sh shojol
  • 21
  • 1
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Mar 04 '22 at 18:33
0

pass value of parameter like this

data : $('#form_id').serialize() + "&parameter1=value1&parameter2=value2"

and so on.

showdev
  • 28,454
  • 37
  • 55
  • 73
Sanjay
  • 9
  • 3
0

Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:

// ...

url: "MyUrl",       //  For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,  
data: 
    $('#myForm').serialize() +
    "&param1="xxx" +
    "&param2="33" +
    "&" + $.param({ paramArray: ["1","2","3"]}, true)
,             

// ...
Dani
  • 1,825
  • 2
  • 15
  • 29
0

encode in js :

  var temp =    $("#pay_property_amount").serialize();
            temp = btoa(temp);

and pass in ajex

 data: { temp_data : temp },

decode in php

    $temp_data = base64_decode($this->input->post('temp_data'));

 if($temp_data){
$temp_data = $this->unserializeForm($temp_data);
 }


function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
    $array = explode("=", $item);
    
    if (preg_match('/(%5B%5D)/', $array[0])) {
          $array[0] = str_replace('%5B%5D','',$array[0]);
          if(array_key_exists($array[0],$returndata)){
                  $returndata[$array[0]][]=$array[1];
          }else{
              $returndata[$array[0]] =array();
              $returndata[$array[0]][]=$array[1];
          }
    }else
    {
        $returndata[$array[0]] = $array[1];
    }
    
    
}

return $returndata;
}
0

Those who want to add new data to form data can use this method. Exemple:

$("form#myForm").submit(function(e){
    e.preventDefault();
    let formData = jQuery("#myForm").serializeArray();
    let newData = [
        {name:"city", value: "Ankara"},
        {name:"jobs", value: "Full-Stack Web Developer"},
        {name:"action", value: "ajax_proccess"} 
    ];
    let postData = formData.concat(newData);

    console.log(formData);
    console.log(newData);
    console.log(postData);

    jQuery(".alert").text("İş: " + postData[4]['value']);
    
    jQuery.ajax({
        url: jQuery("#myForm").attr('action'),
        type: 'POST',
        dataType: 'json',
        data: postData,
        success: function(data) {
            //let response = JSON.parse(data);
            console.log(data);
            alert('Submitted.');
            jQuery(".alert").text(newData[5]);
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="" id="myForm">
<input type="hidden" name="name" value="Mahmut Yüksel">
<input type="hidden" name="surname" value="Mert">
<input type="hidden" name="countary" value="Turkey">
<input type="submit" value="Gönder">
</form>
<div class="alert">İş: </div>
0
cod 100% funcional 
<form id="formElem">
  <input type="text" name="firstName" value="John">
  Imagen: <input type="file" name="picture" accept="image/*">
  <input type="submit">
</form>

<script>
  formElem.onsubmit = async (e) => {
    e.preventDefault();

    let response = await fetch('/article/formdata/post/user-avatar', {
      method: 'POST',
      body: new FormData(formElem)
    });

    let result = await response.json();
    enter code here
    alert(result.message);
  };
</script>
-1

I fix the problem with under statement ; send data with url same GET methode

$.ajax({
    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Aziz Fazli
  • 11
  • 1
-1

You can also use serializeArray function to do the same.

-2

You can create an auxiliar form using jQuery with the content of another form and then add thath form other params so you only have to serialize it in the ajax call.

function createInput(name,value){
    return $('<input>').attr({
        name: name,
        value: value
    });
}
$form = $("<form></form>");
$form.append($("#your_form input").clone());
$form.append(createInput('input_name', 'input_value'));
$form.append(createInput('input_name_2', 'input_value_2'));
....

$.ajax({
    type : 'POST',
    url : 'url',
    data : $form.serialize()
}
Felixuko
  • 60
  • 5