I declare my array:
p.myArray = [];
I add to the array in a loop:
self.myArray.push($(this).data('id')); // [1,2,3,4]
I then send this via AJAX to PHP via POST:
$.ajax({
url: '/gateway',
data: {data: self.myArray},
dataType: 'json',
type: 'POST',
})
I was wondering, do I need to have a key/value pair? Can I just send through the array? Does it need serialising?
asked Aug 11, 2014 at 10:49
panthro
24.2k71 gold badges208 silver badges355 bronze badges
2 Answers 2
Passing an object to data will cause jQuery to serialise it for you.
The array will be available in $_POST['data'][]
It would be clearer if you didn't use the same name for different things.
data: { theArray: self.myArray },
goes to:
$_POST['theArray'][]
answered Aug 11, 2014 at 10:53
Quentin
949k136 gold badges1.3k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Note that if you are using dataType: 'json' your PHP script will have to return JSON serialised data or jQuery will ignore the response.
i.e:
$myArray = $_POST['myArray'];
echo json_encode($myArray);
answered Aug 11, 2014 at 11:09
campsjos
1,4251 gold badge16 silver badges24 bronze badges
Comments
default
data, the value is the array. You code should work - are you having issues with it?$('#formid').serialize();, and if you are working with dynamic variables u have to set every key inside the array