Jules
Jules

Reputation: 544

display php data with jQuery/AJAX

For a project form school I want to build an live score on my site. The live score has to display the surname (voornaam) last name (achternaam) and score of a player.

I made a php file (feed.php) that executes a sql query to select 10 values from a database (2 tables combined) Feed.php will encode and array (json_encode). This is working and when i print the result.

But then I have to make a call from index.html to feed.php with jquery/ajax. I want to refresh the score every second to see if someone got a better score.

I managed to get something displayed but the i've only see "undefined" and it keeps loading. So after a minute I got 60 "scores".

What am I doing wrong and how can I show only 10 records on the page?

So much thanks in advance!

This is the code I use:

index.html:

    <script>
$.get("feed.php", function(data) {
  $("#score")
    .append("<tr><td>" + data.voornaam + "</td><td>" + data.achternaam + "</td><td>" + data.score +"</td></tr>").fadeIn("slow");
}, "json")

</script>

feed.php:

$sql = "SELECT
          game.userID,
          game.score,
          roboshooter.id,
          roboshooter.voornaam,
          roboshooter.achternaam
        FROM
          game, roboshooter
        WHERE
          game.userID = roboshooter.id
        ORDER BY game.score DESC LIMIT 10
      ";

$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_assoc($result))
{
  $return = json_encode(array(
          "voornaam" => $row['voornaam'],
          "achternaam" => $row['achternaam'],
          "score" => $row['score']
          ));
          print_r($return);
}

Jules

Upvotes: 0

Views: 1066

Answers (1)

Gerald Schneider
Gerald Schneider

Reputation: 17797

The print_r renders the json response invalid.

$return = array();
while($row = mysqli_fetch_assoc($result))
{
  $return[] = $row;
}
echo json_encode($return);

You must return a single json object, otherwise it's invalid.

Since this returns an array you'll have to adapt your JavaScript as well:

for (var i = 0; i < data.length; i++) {
  $("#score").append("<tr><td>" + data[i].voornaam + "</td><td>" + data[i].achternaam + "</td><td>" + data[i].score +"</td></tr>").fadeIn("slow");
}

Upvotes: 2

Related Questions