0

I've tried getting information with JSON only with one function, and it works fine. When it becomes two or more though it was pointed out that an array of array should be used.

How can you decode this information?

get.php

$response = array("home"=>$home, "topr"=>$top);
echo json_encode($response);

test.js

$(document).ready(function() {

    $.get("php/get_ratings.php")
    .done(function(data) {
        var results = jQuery.parseJSON(data); // Should I change this?

        $.each(results, function(i, value) { // Or this?
        })
    });
});
1
  • 1
    can you print the data and show here? Commented Jul 17, 2015 at 12:07

1 Answer 1

3

What PHP calls "arrays" are not what most languages call "arrays," including both JSON and JavaScript. Your response will be in this form:

{"home": something, "topr": something}

In your code:

  1. No, you don't need to parse it, jQuery will do that for you if it's being sent correctly (e.g., with Content-Type: application/json).

  2. You can access .homeand .topr properties on the object you receive.

E.g.:

$( document ).ready(function() {

    $.get( "php/get_ratings.php")
    .done(function(data) {  
        // use data.home and data.topr here
    }); 
});

What you do with them depends on what they are, which you haven't shown. If they're numerically-index arrays (what most languages call arrays), your response will look like this:

{"home":["stuff","here"], "topr": ["stuff","here"]}

...and .home and .topr will be JavaScript arrays.

If they're PHP associative arrays like your top level thing, then they'll come through as objects, with properties named after the keys of the associative array.

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.