150

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

0

13 Answers 13

277

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"
})
7
  • 7
    @Falcon What do you mean of coconut in here?
    – Shafizadeh
    Commented Dec 9, 2015 at 0:53
  • how can i change 1 to variable
    – Slatan-ko
    Commented Apr 30, 2016 at 16:33
  • 4
    @Shafizadeh Its a rhyme ( alot - coconut)
    – Adam
    Commented Jul 27, 2016 at 18:08
  • Can you please tell why here no need contentType?? Is that added by default? Commented Sep 2, 2016 at 18:09
  • Yes, form url encoded is the default. See the jquery documentation for more info Commented Sep 3, 2016 at 14:01
90

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.

3
  • 11
    I like this one. It means I don't have to look at an ugly querystring!
    – Greg Woods
    Commented Apr 19, 2013 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
    Commented Apr 5, 2016 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. Commented Oct 15, 2016 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);
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);

    }
});
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);
        }   
    });
});
1
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP.
    – Tyler2P
    Commented Mar 4, 2022 at 18:33
0

pass value of parameter like this

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

and so on.

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)
,             

// ...
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']

-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()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.