1

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 execute, and I have no idea why. No errors on the console, either.

Javascript:

function refreshStats() {
    console.log("number 1");
    $.ajax({
        url: "refreshData.php",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType : 'json',
        data: { },
        cache: false,
        async: true,
        success: function (msg) {
            if(msg){
                console.log("number 2");
                var arr = JSON.parse(msg);
                document.getElementById("interface_stats").innerHTML =
                    "Fatigue: " + arr[0];

            }

        }
    });
}

PHP:

<?php

$username = $_POST['user'];
ini_set('display_errors', 1);
error_reporting(E_ALL);

$con = mysql_connect("localhost","redacted","redacted");
if (!$con)
{
    die('SQL error! Aborting: ' . mysql_error($con));
}
$db = mysql_select_db("aftertheend",$con) or die("Database error! Aborting. Inform the admin.");
$query = "SELECT fatigue, food, water, radiation, condition FROM users WHERE username='TheMightyThor'";
$result = mysql_query($query, $con);

$data = mysql_fetch_row($result);

$stats = [
    "fatigue" => $data[0],
    "food" => $data[1],
    "water" => $data[2],
    "radiation" => $data[3],
    "condition" => $data[4]
    ];

echo json_encode($stats);


?>
Taylor Hill
  • 1,053
  • 1
  • 14
  • 24
  • add an error function that logs the detail to console – Steve Jan 25 '14 at 22:35
  • 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. – John S Jan 25 '14 at 22:36
  • You've set the `dataType` to JSON. jQuery will parse the response for you automatically, so when your `success` function executes your `msg` variable will already be a Javascript object - no need to parse again. I'm surprised that is not showing up in the console. –  Jan 25 '14 at 22:37
  • *Edit* The error code I posted was not related, so I just deleted it. I'm not sure I'm following the suggestions--if the success function isn't being activated, doesn't this suggest that the parsing doesn't matter at this point in the script? Or is the encoding in the PHP script the problem? – Taylor Hill Jan 25 '14 at 22:49
  • remove dataType and contentType from your ajax. Change php $_POST to $_GET and try manually that php works. Add header content type application/json to php output. – Hardy Jan 25 '14 at 22:54
  • You are correct that if the `success` callback is not getting executed, then removing the call to `JSON.parse(msg)` is not going to affect that. – John S Jan 25 '14 at 23:01
  • OK, basic debugging. Change your success function to alert('success'); and your failure function the the equivalent. This will tell you if the php code is failing or not – Steve Jan 25 '14 at 23:16

1 Answers1

3

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);
        }
    }
});
Community
  • 1
  • 1
John S
  • 21,212
  • 8
  • 46
  • 56
  • With those changes, I receive the error message: parsererror SyntaxError {stack: (...), message: "Unexpected token <"}. It seems it keeps trying to treat the JSON object as a string. – Taylor Hill Jan 25 '14 at 23:10
  • 1
    @TaylorHill - It may be that your server is returning an HTML error page, rather than the JSON you are expecting it to return. Since the error page is HTML, the first character is `<`. Temporarily change to `dataType: 'html'` and just put `console.log(msg)` (or whatever you named the parameter) in the `success` callback. – John S Jan 25 '14 at 23:15
  • @TaylorHill - I have added to my answer. – John S Jan 25 '14 at 23:41