52

i am trying to send multiple data using j query $.ajax method to my php script but i can pass only single data when i concatenate multiple data i get undefined index error in my php script tat means the ajax request is made but data is not sent i need to know how should i format multiple data to successively send it to processing script in name vale pair here is what i have written

<script>
  $(document).ready(function() {

    $('#add').click(function () {

      var name = $('#add').attr("data_id");

      var id = $('#add').attr("uid");

      var data = 'id='+ id  & 'name='+ name; // this where i add multiple data using  ' & '

      $.ajax({
        type:"GET",
        cache:false,
        url:"welcome.php",
        data:data,    // multiple data sent using ajax
        success: function (html) {

          $('#add').val('data sent sent');
          $('#msg').html(html);
        }
      });
      return false;
    });
  });
</script>



<span>
  <input type="button" class="gray_button" value="send data" id="add" data_id="1234" uid="4567" />
</span>
<span id="msg"></span>
1
  • I usually just put related items in an object (or leave them in their original object), convert the whole object to a JSON string, and send the JSON string in a parm. On the server side, I have php convert the JSON string back to an object, and voila, I'm in business. Commented Apr 9, 2012 at 18:49

9 Answers 9

110

You can create an object of key/value pairs and jQuery will do the rest for you:

$.ajax({
    ...
    data : { foo : 'bar', bar : 'foo' },
    ...
});

This way the data will be properly encoded automatically. If you do want to concoct you own string then make sure to use encodeURIComponent(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

Your current code is not working because the string is not concocted properly:

'id='+ id  & 'name='+ name

should be:

'id='+ encodeURIComponent(id) + '&name='+ encodeURIComponent(name)
Sign up to request clarification or add additional context in comments.

2 Comments

'id='+ id & 'name='+ name should be changed to 'id='+ id+'&name='+ name
@SaeedAnsari In addition to that, it's a really good idea to sanitize your variables with encodeURIComponent as in the example in the answer. No reason not to protect against XSS attacks.
9

Change var data = 'id='+ id & 'name='+ name; as below,

use this instead.....

var data = "id="+ id + "&name=" + name;

this will going to work fine:)

Comments

6
var data = 'id='+ id  & 'name='+ name;

The ampersand needs to be quoted as well:

var data = 'id='+ id  + '&name='+ name;

3 Comments

+1 as this is the crux of the issue, although I would use the data object suggested in Jasper's answer.
this worked bt i think &(ampersand) in data makes code hard to understand soln given by @SKS is good
@sohaan: Yes, a Javascript object is a better solution.
6

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

Comments

6
var my_arr = new Array(listingID, site_click, browser, dimension);
    var AjaxURL = 'http://example.com';
    var jsonString = JSON.stringify(my_arr);
    $.ajax({
        type: "POST",
        url: AjaxURL,
        data: {data: jsonString},
        success: function(result) {
            window.console.log('Successful');
        }
    });

This has been working for me for quite some time.

Comments

5
var value1=$("id1").val();
var value2=$("id2").val();
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"

Comments

2

you can use FormData

take look at my snippet from MVC

var fd = new FormData();
fd.append("ProfilePicture", $("#mydropzone")[0].files[0]);// getting value from form feleds 
d.append("id", @(((User) Session["User"]).ID));// getting value from session

$.ajax({
    url: '@Url.Action("ChangeUserPicture", "User")',
    dataType: "json",
    data: fd,//here is your data
    processData: false,
    contentType: false,
    type: 'post',
    success: function(data) {},

Comments

0
var CommentData= "u_id=" + $(this).attr("u_id") + "&post_id=" + $(this).attr("p_id") + "&comment=" + $(this).val();

Comments

-1
  var value1=$("id1").val();
  var value2=$("id2").val();
    data:"{'data1':'"+value1+"','data2':'"+value2+"'}"

You can use this way to pass data

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.