Skip to content Skip to sidebar Skip to footer

Passing An Array From Php To Javascript Using Jquery & Json

I've got a game which refreshes info every 10 seconds from a MySQL database. There will be a JS function which is called each time this happens. I can't get the success function to

Solution 1:

I think your PHP is returning an error, rather than the JSON you are expecting. Since you have dataType: 'json', jQuery attempts to parse the response, but fails. When that happens, jQuery does not call the success callback.

If you can, use Firebug to see what is being returned by the ajax call. Another way would be to temporarily change to dataType: 'html' and then change your success callback to:

success: function(msg) { alert(msg); }

Hopefully when you see the message being returned, it will help identify the problem. One thing you should do though, is add code to handle the cases where the query fails to execute and where no row is fetched from the database. You could add the following code to the PHP file:

$result = mysql_query($query, $con);

if (!$result) {
    die('Could not run query: ' . mysql_error($con));
}

if (mysql_num_rows($result) < 1) {
    echo'null';
    exit;
}

$data = mysql_fetch_row($result);

There are also a few issues with the Ajax call though:

(1) You are specifying contentType: "application/json; charset=utf-8", but then you are not sending JSON. You should do something like this:

data: JSON.stringify({}),

But if you do this, you cannot get the data on the server using the $_POST function. Therefore, you might want to get rid of the contentType setting instead. See this SO answer for more information.

(2) When you specify dataType: 'json', JQuery will parse the response to an object before calling the success callback, so the msg parameter should already be an object. Therefore, you should not call JSON.parse(msg).

(3) You are returning an associative array from the PHP file. That will be converted to a JavaScript object, not an array.

I think you should try the following:

$.ajax('refreshData.php', {
    type: 'post',
    dataType: 'json',
    data: { },
    cache: false,
    success: function (data) {
        if (data) {
            $('#interface_stats').html('Fatigue: ' + data.fatigue);
        }
    }
});

Post a Comment for "Passing An Array From Php To Javascript Using Jquery & Json"