1

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?

4
  • 2
    You do need a key/value pair, but you're sending one. The key is data, the value is the array. You code should work - are you having issues with it? Commented Aug 11, 2014 at 10:50
  • No issues, I was just wondering if I had to have a key/value pair AND if I need to seralize the array? Commented Aug 11, 2014 at 10:52
  • jQuery will serialise the array for you, so you don't need to worry about it. Commented Aug 11, 2014 at 10:52
  • if you are working with static inputs use $('#formid').serialize(); , and if you are working with dynamic variables u have to set every key inside the array Commented Aug 11, 2014 at 10:52

2 Answers 2

3

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'][]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.