I currently have a PHP file that accesses my MySQL database and pulls out the Names and Scores for each player and stores them in an array.
//This query grabs the top 10 scores, sorting by score and timestamp.
$query = "SELECT * FROM Score ORDER by score DESC, ts ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
//We find our number of rows
$result_length = mysql_num_rows($result);
//And now iterate through our results
for($i = 0; $i < $result_length; $i++)
{
$row = mysql_fetch_array($result);
echo $row['name'] . "\t" . $row['score'] . "\n"; // And output them
}
What is the best way for me to get both the name and the score from the PHP File and store them in a Javascript Array?
3 Answers 3
The best way to store them is store them in json. Use following function
json_encode(arrayname);
and in html use
$.parsejson(responsevariable);
to get original value.
Comments
I would suggest to give json_encoded array to javascript variable (json_encode()), and use javascript json decoding functionality, so you will get what you want :)
Comments
Create a result variable
$results = array();
Store your results in it in your loop
array_push($results, array("name" => $row["name"], "score" => $row["score"]));
At the end return it with
echo json_encode($results);
When you get the response on the front end, you can take the response data and JSON.parse() it to turn it into a variable that you can access
var results = JSON.parse(data);
results.forEach(function(result){
console.log( result.name +" - "+ result.score );
});
5 Comments
//Leaderboard $.get( "HighScores/TopScores.php", function(data) { var results = JSON.parse(data); console.log(2); results.forEach(function(result){ console.log( result.name +" - "+ result.score ); console.log(1) }); }, "json" ); But my Game doesn't seem to print anything out to the Console, not Name, Scores, "1" or "2"?$.ajax({ url: 'HighScores/TopScores.php', type: 'get', success: function(data){ console.log(data); results = JSON.parse(data); console.log(data); LoadedName = results[0].name; LoadedScore = results[0].score; } }); Which outputs: [{"name":"Conor","score":"100"},{"name":"Mark","score":"100"}]Uncaught SyntaxError: Unexpected token < On Line 1 of my HTML page (Which just loads the Javascript files)
$row?//Leaderboard $.get( "HighScores/TopScores.php", function(data) { var results = JSON.parse(data); console.log(2); results.forEach(function(result){ console.log( result.name +" - "+ result.score ); console.log(1) }); }, "json" );But my Game doesn't seem to print anything out to the Console, not Name, Scores, "1" or "2"?