-4

I have an array like this in php :

Array
(
    [week] => 15
    [showing] => present
    [ignore_team_id] => Array
        (
            [0] => 362
            [1] => 343
            [2] => 352
            [3] => 331
        )

    [event_pasted_team_id] => Array
        (
        )

    [old_data] => old_data
)

I want to get this array back in php from ajax. This is what I did so far.

I just encode the array into json and saved it in hidden field using json_encode();

<input id='myArray' type='hidden' name="myArray" value='<?php echo json_encode($myArray);?>' /> 

In javascript:

function ajaxloadPlage(outputId,dataTransfer){
            myArrayVal = jQuery('#myArray').val();
            strify = JSON.stringify(myArrayVal);
            jQuery.get( myapp.ajaxurl+'?'+dataTransfer,{action:'getPlayerRaterData','getArr':strify}, function( data ) {
            //business login goes here
                });
    }

Back in PHP:

if($_GET['getArr']){
    $getArr = $_GET['getArr'];
    echo '<pre>';print_r($getArr);
}

Its print like this:

\"{\\\"week\\\":15,\\\"showing\\\":\\\"present\\\",\\\"ignore_team_id\\\":[362,343,352,331],\\\"event_pasted_team_id\\\":[],\\\"old_data\\\":\\\"old_data\\\"}\"

How can I get the valid array back?

Rahul
  • 440
  • 7
  • 24

2 Answers2

0

You have encoded the array in json during sending but not decoded in back php. try like this..

PHP:

<?php
if($_GET['getArr']){
    $getArr = $_GET['getArr'];
    echo '<pre>';print_r(json_decode($getArr));
}
?>

Hope this will solve ur issue.

Amit Rajput
  • 2,061
  • 1
  • 9
  • 27
0

myArrayVal is already a JSON string, you don't need to call JSON.stringify. You should call JSON.parse() to convert it to an object. $.get() will then URL-encode the object, and PHP will decode this when it sets $_GET['getArr'].

function ajaxloadPlage(outputId,dataTransfer){
    myArrayVal = jQuery('#myArray').val();
    myArray = JSON.parse(myArrayVal);
    jQuery.get( myapp.ajaxurl+'?'+dataTransfer,{action:'getPlayerRaterData','getArr':myArray}, function( data ) {
        //business login goes here
    });
}
Barmar
  • 741,623
  • 53
  • 500
  • 612