Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send multiple data with $.ajax() jquery

Tags:

jquery

ajax

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>
like image 553
sohaan Avatar asked Apr 09 '12 18:04

sohaan


People also ask

How can send multiple values by ajax in jquery?

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

How can I pass two values from ajax to php?

You can get text box value using $("input[name='another']"). val() and it can be passed to ajax call parameter which is mentioned in code. Show activity on this post. Show activity on this post.


3 Answers

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)
like image 127
Jasper Avatar answered Oct 08 '22 14:10

Jasper


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

use this instead.....

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

this will going to work fine:)

like image 9
Selvakumar Arumugam Avatar answered Oct 08 '22 14:10

Selvakumar Arumugam


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

The ampersand needs to be quoted as well:

var data = 'id='+ id  + '&name='+ name;
like image 6
xbonez Avatar answered Oct 08 '22 14:10

xbonez