2

I'm trying to pass an array in an ajax request, but apparently it doesn't work...

        $.post("process.php", array,
            function(data) {
                document.getElementById("output").innerHTML = JSON.parse(data);
            });

My question is, how to use the data sent in the process file?
The array is built like that: [key (0/1/2...)] => ["prod_id"]. The id varies.
I read somewhere using $_POST["key"]; would work, but it doesn't.

It'd be even better if I could just get the array as is in the process file.

process.php (really basic - just to check wether it's working or not.):

<?php print($_POST["test"]); ?>

1
  • I don't know about sending array with jQuery but the $_POST variable would work. When you pass, you should get like $_POST['key'][0]. Commented Jun 24, 2012 at 14:28

4 Answers 4

2

Try to pass {data: array} instead of array. The AJAX call expects an object.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to build an Object of array elements. for example:

You can also try like:

{ 'key[]': [1, 2, 3] }

OR

{ key: [1,2,3] }

Read more about $.post()

Comments

1

In order to receive data in php you need to send key/value pairs, however you are only sending a value.

You receive in php with $_POST[key] which will return the value for that key.

JS:

$.post("process.php", {myAray: array}, function(data) {
            $("#output").html(data);
});

php

   $array= $_POST['myArray'];

To return this array from php as text just to test your ajax can use var_dump( $_POST) or var_dump($array);

If you intend to receive JSON in response from server, you do not need to use JSON.parse , jQuery will parse json internally. However you would need to add "json" as dataType argument to $.post

$.post("process.php", {myAray: array}, function(data) {
            /* loop over json here*/
},'json');

Comments

1

if you want to pass an array, you have to "prepare" the key as following:

{'key[]' : ['value1', 'value2', 'value3']}

the same way you'd do it, when you want to pass an array in a form and set the name-attribute to "key[]".

2 Comments

no disrespect … bro. you were mentioning it while i was writing my post. do you feel better when i delete my post?
Just fine, never do that, I don't bother

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.