Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm looking for the best way to pass php array to javascript.

I'm making a RPG, and when they login, I'd like to return their saved data from database and store in an array on javascript side:

To get data, I do:

$.getJSON("php/CRUD.php", {"_functionToRun" : ""},
    function (returned_data) {
        game.data.dataArray.push(returned_data.split(" "));
        log("1: " + game.data.dataArray); //output: `1: 120,mymap2` 
        log("2: " + game.data.dataArray[0]); //output: `2: 120,mymap2`
    }
);

PHP:

    $qry = 
        'SELECT * 
        FROM userstats
        WHERE id_user_fk ="' . $_SESSION['userid'] . '"
        LIMIT 1';

    $result = $mysqli->query($qry) or die(mysqli_error($mysqli));

    while ($row = $result->fetch_assoc()) {
        $message =  $row['experience'] . $row['levelname'];
    }   

 echo json_encode($message);

1) Is this the best way to get a set of values into a js array?

2) Why can't I access a certain data element of game.data.dataArray using game.data.dataArray[0].

These give the same output of 1: 120,mymap2

        log("1: " + game.data.dataArray);
        log("2: " + game.data.dataArray[0]);

Should returned_data.split(" ") split the returned string into two array elements?


EDIT: Okay I've done echo json_encode($message); and it returns with quotes, but still returns same results for game.data.dataArray and game.data.dataArray[0]

1: "120,mymap2" 
2: "120,mymap2" 

I've also changed the function to $.getJSON


Changed again to

    $qry = 
        'SELECT * 
        FROM userstats
        WHERE id_user_fk ="' . $_SESSION['userid'] . '"';

    $result = $mysqli->query($qry) or die(mysqli_error($mysqli));

    while ($row = $result->fetch_assoc()) {
        $array[] =  $row['experience'] . $row['levelname'];
        die(json_encode($array[]));
    }   

and JS is:

$.getJSON("php/CRUD.php", {"_functionToRun" : ""},
    function (returned_data) {
        game.data.dataArray.push(returned_data.split(" "));
        log("1: " + game.data.dataArray);
        log("2: " + game.data.dataArray[0]);
    }
);

Outputs:

Uncaught melonJS: level <br />
<font size='1'><table class='xdebug-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-...<omitted>...nd 
share|improve this question
3  
You should use json_encode function. –  hidden_4003 1 hour ago
    
@hidden_4003 please see update –  Growler 1 hour ago
    
The php you posted does not output anything, what exactly are you echoing? –  jeroen 1 hour ago
    
@jeroen please see above –  Growler 1 hour ago
add comment

2 Answers

up vote 2 down vote accepted

If you use $.getJSON and you provide valid json, you don't need to parse anything, so you can change your php to:

if ($row = $result->fetch_assoc()) {
    echo json_encode($row);
    exit;    // You're limiting the number of rows to 1, so there is no need to continue
}

And the javascript:

$.getJSON("php/CRUD.php", {"_functionToRun" : ""},
    function (returned_data) {
        // you can push `returned_data` to an array / add it to an object,
        // but then you need to keep track of its index
        log("1: " + returned_data.experience); //output: `1: 120` 
        log("2: " + returned_data.levelname); //output: `2: mymap2`
    }
);
share|improve this answer
1  
Had no idea you can do returned_data.experience, and access the returned data's properties. Is that because you're returning it as JSON, a js readable object? –  Growler 42 mins ago
    
@Growler Even better; even if you use the "normal" $.ajax() method, jQuery will make an intelligent guess and parse your json. Although if you want to do it correctly, you use dataType: 'json' or $.getJSON. You just need to make sure no other output is sent back apart from the json (like warnings, etc.). –  jeroen 36 mins ago
add comment

What you need to do is, change this code:

while ($row = $result->fetch_assoc()) {
    $message =  $row['experience'] . $row['levelname'];
}

To make it as an array:

while ($row = $result->fetch_assoc()) {
    $message[] =  $row['experience'] . $row['levelname'];
}

So, $message now becomes an array. You need to output this to the client. You can do that using:

die(json_encode($message));

The reason is, in your code, it will output only the last one.

share|improve this answer
    
Praveen, thanks. Please see above edit. It's not working. –  Growler 48 mins ago
    
What's the response of the PHP page? –  Praveen Kumar 48 mins ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.