Asaf
Asaf

Reputation: 2035

How to use an array sent with an jQuery's AJAX post request + php?

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"]); ?>

Upvotes: 2

Views: 301

Answers (4)

charlietfl
charlietfl

Reputation: 171669

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

Upvotes: 1

Emanuel Kluge
Emanuel Kluge

Reputation: 705

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[]".

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

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

Upvotes: 2

Cranio
Cranio

Reputation: 9847

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

Upvotes: 2

Related Questions