0

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.

var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
    $("button").click(function () {
        $.ajax({
            type: "POST",
            url: "getResult.php",
            data: {
                testData: data
            },
            success: function (data, status) {
                alert("Data: " + data + "\nStatus: " + status);
            }
        });
        return false;
    });
});

The server side [PHP] code is

$myArray = $_POST["testData"];
echo $myArray; 

However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements? Pls help.

thecodedeveloper.com
  • 3,220
  • 5
  • 36
  • 67
Jithu
  • 111
  • 3
  • 11
  • 2
    you'd need to JSON.stringify() the array in JS, then json_decode() it in php. that way you'll end up with a native PHP array and access it like any other array. – Marc B Feb 14 '13 at 18:28
  • ^^ is right. Heres a similar disucssion: http://stackoverflow.com/questions/2013728/passing-javascript-array-to-php-through-jquery-ajax – tymeJV Feb 14 '13 at 18:28
  • Isn't there some way of doing this without json? How does jQuery send over checked checkbox input values? – Kevin B Feb 14 '13 at 18:34
  • What happens if you name the variable `testData[]` instead? – Blazemonger Feb 14 '13 at 18:35

4 Answers4

0

JS:

JSON.stringify(data)

PHP:

$myArray = json_decode($_POST['data']);
SeanWM
  • 16,789
  • 7
  • 51
  • 83
0

What you need to do is convert the JavaScript array to JSON and then send over that JSON. On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.

On your client side change one line:

data: {testData : JSON.stringify(data)},

On your server side do:

$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
Adam
  • 43,763
  • 16
  • 104
  • 144
0

For simple structures you can use jQuery Param

data : $.param({testData:data})

With this you should be able to access your data with

echo $_POST["testData"][0]...[2];
Kodemon
  • 370
  • 2
  • 11
0

Try this when passing JS vars by ajax.

use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.

you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.

use :

 var data = ['test1','test2','test3'];
 data = JSON.stringfy(data);

at the PHP:

     $data = var_post('test_data');
     $data=json_decode($data);
     $print_r($data);
Meta_data
  • 558
  • 3
  • 14