146

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?

5
  • 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. Commented May 22, 2011 at 2: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. Commented May 22, 2011 at 2:37
  • Using firebug really helped, totally forgot about checking my page with it. :/ Commented May 22, 2011 at 3:08
  • What is the use of ** in front and at the end of the data param? Commented Jul 21, 2014 at 8: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! Commented Dec 19, 2014 at 16:03

12 Answers 12

285

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.

Sign up to request clarification or add additional context in comments.

5 Comments

He points out specifically in the question: "i've tried all sorts of stuff: data: {status: status, name: name},"
I was just pointing out the correct syntax and saying that the problem must be something else not the syntax
Seems my syntax was correct, I believe i've made a very dumb SQL mistake.
Re: syntax, note that a key name is a '-' e.g. data: { site-name: "StackOverflow" } won't work.
From the docs "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."
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
      }
 });

2 Comments

.serialize() is not defined!
what if we want to pass some more data along with serialize function Exaample: $.ajax({ type: "POST", url: 'retrivedata.php', action: "c", id:"index", data: {$(this).serialize(), id: "index", action: "c"} }); });
10

Try with quotes:

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

It must work fine.

1 Comment

+1. BTW this actually data: {status: "status", name: "name"} api.jquery.com/jquery.ajax
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.

1 Comment

This solution worked for me when trying to pass an array over ajax. Joining it into a string was the solution. Thanks!
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 );
});

Comments

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

Comments

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

1 Comment

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.
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.

Comments

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) {...

Comments

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

Comments

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

1 Comment

Some explanation perhaps?
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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.