0

I am trying to make a site that dynamically creates information using the jQuery ajax call $.getJson and the jQuery template plugin. In my index.html page, I have some of the following code:

        $(document).ready(function() {
            var jsonData ="string";

            $.getJSON("load.php", function(data) {
                jsonData = data;
                console.log(jsonData);
            });

            console.log(JSON.stringify(jsonData));
            // Load template from our templates folder,
            // and populate the data from the post object.
            $("#test").loadTemplate('#template', jsonData);

        });

The ajax call executes the load.php, which has some of the following code:

//extract user ratings and respective movies
$_SESSION['username'] = $username;
$user_query = mysqli_query($link, "SELECT * FROM Client WHERE Username = '$username'");
$user_row = mysqli_fetch_array($user_query);
$user_id = $user_row['ID'];

$query = mysqli_query($link, "SELECT * FROM Ratings INNER JOIN Movie ON Ratings.Movie_ID = Movie.MovieID WHERE Client_ID = $user_id ORDER BY Rating DESC");
//adding movies to array list
$result =  array();
while ($row = mysqli_fetch_array($query))
{
    $movie = $row['MovieURL'];
    $rating = $row['Rating'];
    array_push($result, array('moviePicture' => $movie, 'movieRating' => $rating));
}
//converting array list to json and echoing it
echo json_encode($result);

I have tested the $result and it does create a json object with all of the data that it is supposed to. However, when the javascript is run in the index.html page, jsonData does not change its value from 'string'(when I check the console log). I believe the problem is with the function(data), since it does not log the console command I have in there. Any help would be appreciated.

koleary
  • 171
  • 3

1 Answers1

0

Proper code:

$(document).ready(function() {
    var jsonData ="string";

    $.getJSON("load.php", function(data) {
        jsonData = data;
        $("#test").loadTemplate('#template', jsonData);
    });
});

The problem with your code is, that you call loadTemplate before you got reply from load.php

JimiDini
  • 2,039
  • 12
  • 19