user2810718
user2810718

Reputation: 71

read jquery array in php

i am trying to retrieve the value of array via post in php script.

var data = [];
table.rows({ selected: true }).every(function(index){
    // Get and store row ID
    data.push(this.data()[0]);  //create a 1 dimensional array
});

//send data via ajax    
$.ajax({                                      
      url: '/...../...',                  
      type: 'POST',   
      data: {userid:data},                      
      dataType: 'json',                       

In my PHP script so far I am unable to decode the array. Have tried many ways

$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
    $userid= $value;             //for now just trying to read single item 
}

I have tried print_r($myArray ); this sucessfully prints array contents to screen.

I am trying to retrieve the values for processing! Kindly point me in the right direction

Upvotes: 1

Views: 1059

Answers (5)

mondersky
mondersky

Reputation: 471

According to your var_dump :

array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }

and if we assume "assssssss,camo,castor" are 3 different usernames. You should use this:

 $userids=explode(",",$myArray->userid);
    foreach($userids as $userid){
        // use $userid
   }

Upvotes: 0

Tobi Obeck
Tobi Obeck

Reputation: 2317

The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.

You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876

$phpArray = json_decode($myArray, true);

Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php

Upvotes: 1

Esten
Esten

Reputation: 1395

You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.

$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
    $userid= $value;             //for now just trying to read single item 
}

I believe you should also be able to find your values in $_POST

Upvotes: 0

Ambulare
Ambulare

Reputation: 933

I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.

Upvotes: 1

T.Todua
T.Todua

Reputation: 56371

simply use:

echo json_encode($myArray);

Upvotes: 0

Related Questions