Reputation: 1512
I want to retrieve data from my SQL database and use it on my HTML page.
I have a php script get_score.php
like this:
<?php
$con = mysqli_connect( "localhost", "xxx1", "xxx2", "xxx3");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `name`, `score` FROM crossstreet ORDER BY `score` DESC LIMIT 5";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$output = ($row["name"]);
}
mysqli_free_result($result);
echo json_encode($result);
mysqli_close($con);
?>
And then I want to retrieve the data I via JQuery. I have read about the cross-origin issue but the data I retrieve and the html/Jquery are on the same server.
$.get("get_score.php", function( data ) {
console.log(window[data]);
}, "json" );
This returns undefined
. If I make it $(data)
it returns an object like the one on this screenshot.
Where is my mistake; how can I just get the data from the server to use in html?
Upvotes: 1
Views: 97
Reputation: 780724
You need to make $output
an array so you get all the rows.
$output = array();
while ($row = mysqli_fetch_assoc($result)) {
$output[] = $row['name'];
}
Then you should echo this:
echo json_encode($output);
And in your jQuery code, you should do console.log(data);
Upvotes: 2
Reputation: 3827
mysqli_free_result($result);
echo json_encode($result);
i think this is the problem. Try to reverse the order. You are making the result free before using it. Do like this, instead of the above .
echo json_encode($result);
mysqli_free_result($result);
Upvotes: 0