145

I'm stuck: I'm trying to submit a form using AJAX, but I can't find a way to send multiple data fields via my AJAX call.

$(document).ready(function() {
  $("#btnSubmit").click(function()  {
    var status = $("#activitymessage").val();
    var name = "Ronny";
    $.ajax({
      type: "POST",
      url: "ajax/activity_save.php",
      **data: "status="+status+"name="+name"**,
      success: function(msg) {...

I've tried all sorts of stuff:

data: {status: status, name: name},

Or even stuff like this just for testing purposes:

data: "status=testing&name=ronny",

But whatever I try, I get nothing in my activity_save.php thus nothing in my SQL.

So, what's the correct syntax to put more lines of data in my AJAX call?

TylerH
  • 20,799
  • 66
  • 75
  • 101
deadconversations
  • 1,927
  • 2
  • 13
  • 14
  • Both of the secondary forms of handling the input data are valid. How are you accessing this on the PHP side? You may consider an HTTP sniffer (Fiddler on the PC, something like HTTPScoop on a Mac), which will show you exactly what is moving across the wire. – John Green May 22 '11 at 02:33
  • I would suggest using firebug/chrome to debug your post data. Make sure you are getting a HTTP Code 200 and that the form data is being posted at your think it should be. If everything looks correct with the post data, I would start trying to debug your PHP server side code. –  May 22 '11 at 02:37
  • Using firebug really helped, totally forgot about checking my page with it. :/ – deadconversations May 22 '11 at 03:08
  • What is the use of ** in front and at the end of the data param? – heinkasner Jul 21 '14 at 08:56
  • 1
    @heinkasner, I think the ** is just there to show the reader which line the author would like to emphasize. The ** would have to be removed when the code is ready to be saved to file! – Mark Dec 19 '14 at 16:03

12 Answers12

281

The correct syntax is:

data: {status: status, name: name},

As specified here: http://api.jquery.com/jQuery.ajax/

So if that doesn't work, I would alert those variables to make sure they have values.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Avitus
  • 15,640
  • 6
  • 43
  • 53
  • 4
    He points out specifically in the question: "i've tried all sorts of stuff: `data: {status: status, name: name},`" – Ry- May 22 '11 at 02:31
  • 21
    I was just pointing out the correct syntax and saying that the problem must be something else not the syntax – Avitus May 22 '11 at 02:33
  • 3
    Seems my syntax was correct, I believe i've made a very dumb SQL mistake. – deadconversations May 22 '11 at 02:40
  • 2
    Re: syntax, note that a key name is a '-' e.g. `data: { site-name: "StackOverflow" }` won't work. – moey Dec 27 '11 at 13:49
  • 1
    From the [docs](http://api.jquery.com/jquery.ajax/) *"The data option can contain either a query string of the form `key1=value1&key2=value2`, or an object of the form `{key1: 'value1', key2: 'value2'}`. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent."* – Jay Blanchard May 11 '16 at 20:15
38

You can send data through JSON or via normal POST, here is an example for JSON.

 var value1 = 1;
 var value2 = 2;
 var value3 = 3;   
 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "yoururlhere",
      data: { data1: value1, data2: value2, data3: value3 },
      success: function (result) {
           // do something here
      }
 });

If you want to use it via normal post try this

 $.ajax({
      type: "POST",
      url: $('form').attr("action"),   
      data: $('#form0').serialize(),
      success: function (result) {
         // do something here
      }
 });
Aaron Meese
  • 1,670
  • 3
  • 22
  • 32
k-dev
  • 1,657
  • 19
  • 30
10

Try with quotes:

data: {"status": status, "name": name}

It must work fine.

Alberthoven
  • 2,798
  • 1
  • 24
  • 29
  • 4
    +1. BTW this actually data: {status: "status", name: "name"} http://api.jquery.com/jquery.ajax/ – Amir May 18 '15 at 18:25
7
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';

after that you can do like:

var new_countries = countries.join(',')

after:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: new_countries,
    ...

This thing work as JSON string format.

Shahin
  • 12,543
  • 39
  • 127
  • 205
  • This solution worked for me when trying to pass an array over ajax. Joining it into a string was the solution. Thanks! – Brian Powell Feb 17 '15 at 15:23
3

This one works for me.

Here's my PHP:

<div id="pageContent">
  <?php
    while($row = mysqli_fetch_assoc($stmt)) {
  ?>
  <br/>
  <input id="vendorName_" name="vendorName_<?php echo $row["id"]; ?>" value='<?php echo $row["vendorName"]; ?>'>
  <input id="owner_" name="owner_<?php echo $row["id"]; ?>" value='<?php echo $row["owner"]; ?>'>
  <input id="city_" name="city_<?php echo $row["id"]; ?>" value='<?php echo $row["city"]; ?>'>
  <button id="btn_update_<?php echo $row["id"]; ?>">Update</button>
  <button id="btn_delete_<?php echo $row["id"]; ?>">Delete</button>
  <?php
    }
  ?>
  </br></br>
  <input id = "vendorName_new" value="">
  <input id = "owner_new" value="">
  <input id = "city_new" value="">
  <button id = "addNewVendor" type="submit">+ New Vendor</button>
</div>

Here's my jQuery using AJAX:

$("#addNewVendor").click(function() {
  alert();
  $.ajax({
    type: "POST",
    url: "create.php",
    data: {vendorName: $("#vendorName_new").val(), owner: $("#owner_new").val(), city: $("#city_new").val()},
    success: function(){
      $(this).hide();
      $('div.success').fadeIn();
      showUsers()
    }
  });
});
dda
  • 6,030
  • 2
  • 25
  • 34
3

According to http://api.jquery.com/jquery.ajax/

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});
dda
  • 6,030
  • 2
  • 25
  • 34
Amir
  • 8,821
  • 7
  • 44
  • 48
2

I am a beginner at ajax but I think to use this "data: {status: status, name: name}" method datatype must be set to JSON i.e

$.ajax({
type: "POST",
dataType: "json",
url: "ajax/activity_save.php",
data: {status: status, name: name},
Shan
  • 41
  • 3
  • 3
    Welcome to stack overflow. `dataType` is the content type response you expect to get from the **server** - not what you're sending. The data you're sending will **always** be converted to `foo=bar&bar=foo`. – h2ooooooo Sep 26 '13 at 16:14
1

I am new to AJAX and I have tried this and it works well.

function q1mrks(country,m) {
  // alert("hellow");
  if (country.length==0) {
    //alert("hellow");
    document.getElementById("q1mrks").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
  //mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
  xmlhttp.send();
}
dda
  • 6,030
  • 2
  • 25
  • 34
1

Use this

data: '{"username":"' + username + '"}',

I try a lot of syntax to work with laravel it work for me for laravel 4.2 + ajax.

1

Try this:

$(document).ready(function() {
  $("#btnSubmit").click(function() {
    var status = $("#activitymessage").val();
    var name = "Ronny";
    $.ajax({
      type: "POST",
      url: "ajax/activity_save.php",
      data: {'status': status, 'name': name},
        success: function(msg) {...
dda
  • 6,030
  • 2
  • 25
  • 34
1

Try to use :

$.ajax({
    type: "GET",
    url: "something.php",
    data: { "b": data1, "c": data2 },   
    dataType: "html",
    beforeSend: function() {},
    error: function() {
        alert("Error");
    },
    success: function(data) {                                                    
        $("#result").empty();
        $("#result").append(data);
    }
});
pistou
  • 2,799
  • 5
  • 33
  • 60
0

Here's what works for me after 2 days of head-scratching; why I couldn't get the AJaX 'data' setting to send two key/values (including a variable containing raw image data) was a mystery, but that seems to be what the jQuery.param() function was written for;

create a params array with your variables, without quotes:

var params = { key_name1: var_1, key_name2: var_2  }; // etc.

var ser_data = jQuery.param( params );   // arbitrary variable name

Use variable ser_data as your data value;

      $.ajax({
       type: 'POST',
       url: '../php_handler_url.php',
       data: ser_data,
    }).success(function(response) {
       alert(response);
    });

Documentation is here: https://api.jquery.com/jQuery.param/

Hope that helps!

big_lion
  • 23
  • 5