How to send multiple data fields via Ajax?

JquerySqlAjax

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Solution 3 - Jquery

Try with quotes:

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

It must work fine.

Solution 4 - Jquery

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.

Solution 5 - Jquery

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

Solution 6 - Jquery

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

Solution 7 - Jquery

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

Solution 8 - Jquery

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

Solution 9 - Jquery

Use this

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

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

Solution 10 - Jquery

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

Solution 11 - Jquery

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

Solution 12 - Jquery

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeadconversationsView Question on Stackoverflow
Solution 1 - JqueryAvitusView Answer on Stackoverflow
Solution 2 - Jqueryk-devView Answer on Stackoverflow
Solution 3 - JqueryAlberthovenView Answer on Stackoverflow
Solution 4 - JqueryShahinView Answer on Stackoverflow
Solution 5 - JqueryTheGreenGentlemanView Answer on Stackoverflow
Solution 6 - JqueryAmirView Answer on Stackoverflow
Solution 7 - JqueryShanView Answer on Stackoverflow
Solution 8 - Jqueryuser2155518View Answer on Stackoverflow
Solution 9 - JqueryKanin PeanviriyakulkitView Answer on Stackoverflow
Solution 10 - Jqueryuser4184048View Answer on Stackoverflow
Solution 11 - Jqueryuser8161624View Answer on Stackoverflow
Solution 12 - Jquerybig_lionView Answer on Stackoverflow