0

I have an array in Javascript which is passed to a PHP script via Ajax.

In file.js:

var params = {};
params["apples"] = "five";
params["oranges"] = "six";
params["pears"] = "nine";
var ajaxData = {data : params};
fetchData(ajaxData);

function fetchData(arg) {
    $.ajaxSetup ({
        cache: false
    });

    request = $.ajax ({
        type: "GET",
        url: "script.php",
        data: arg,
    });


    request.done(function(response){
            $("#somediv").text(response);
    });

    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });
}

In script.php:

<?php
    $data = json_decode(stripslashes($_GET['data']));
    var_dump($data);
?>

The result of the var_dump is:

object(stdClass)#1 (3) { ["apples"]=> string(4) "five" ["oranges"]=> string(3) "six" ["pears"]=> string(4) "nine" }

But I don't want to use an object, I want to use it the same way I used the data in Javascript (ie: being able to do:

$apples = $data["apples"]

Is there any way to deal with this data as an array and not an object right from the get-go? If not, how do I "convert" what I have now into the same associative array as I had in Javascript?

Thanks.

1
  • That is not a Javascript array. Commented Feb 10, 2014 at 15:14

1 Answer 1

6

PHP's json_decode takes an optional second argument to do this:

assoc
When TRUE, returned objects will be converted into associative arrays.

Problem solved, by reading the documentation!

$data = json_decode(stripslashes($_GET['data']), true);
//                                             ^^^^^^
Sign up to request clarification or add additional context in comments.

Comments

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.