Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery post array

Am wondering how to post an array using $.ajax. My array is something like this:

var a = new Array();
a['test'] = 1;
a['test2'] = 2;
and so on...

I tried:

$.ajax({
  url: baseUrl+"chat.php",
  data: { vars: a},
  type: 'post',
  success: function(data) {
alert(data);
}});

Any suggestions?

like image 906
Alec Smart Avatar asked Jun 04 '09 13:06

Alec Smart


3 Answers

Try this one:

var a = {}; a['test'] = 1; a['test2'] = 2;  // or   var a = {}; a.test = 1; a.test2 = 2;  // or   var a = {     test : 1,     test2 : 2 };  $.ajax({   url: baseUrl+"chat.php",   data: a,   type: 'post',   success: function(data) {     alert(data);   } }); 

You may then access the data in your PHP script like this:

$_POST['test']; $_POST['test2']; 
like image 126
Ionuț G. Stan Avatar answered Sep 20 '22 02:09

Ionuț G. Stan


I used this:

var newArray = new Array(); newArray.push("item1"); newArray.push("item2"); newArray.push("item3");  $.ajax({       type: "POST",     url: urlToPost,     data: JSON.stringify(newArray),     contentType: "application/json"    }); 
like image 44
Aldo Avatar answered Sep 21 '22 02:09

Aldo


I prefer doing it this way:

ie.

var data = [{ name: 'test1', value: 'test data' }, { name: 'test2', value: 'test data' }];

$.ajax({  
    type: 'POST',
    url:  'url',
    data: data,
   });

Server side (PHP): $_POST['test1']; $_POST['test2'];

like image 31
Tom Avatar answered Sep 22 '22 02:09

Tom