1

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. enter image description here

Where is my mistake; how can I just get the data from the server to use in html?

1
  • 2
    You need to json_encode($output) not $result Commented May 26, 2015 at 11:08

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0
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);

1 Comment

$result is not useful to send to the client.

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.