Ali
Ali

Reputation: 1058

Fix jQuery setInterval and JSON

I wrote this code to get new data from a database, but I don't know what is wrong with this code and why I'm getting the following error in the browser console.

jQuery Code:

$(document).ready(function() {
    setInterval(function() {
        var lastdate = $("#countcomment").attr("loadtime");
        $.post("update.php",{ajax:"1", lastdate:lastdate},function(data){
            if(data.getnew){
                $('#countcomment').html(data.getnew);
                $('#countcomment').attr('loadtime', ""+data.new)
            }
        }, "json");
    }, 1000);
}); 

PHP:

$database = $db->super_query("
    SELECT count(*) as count 
    FROM ".PREFIX."_comments 
    WHERE date >= '$real_date' 
");

$newcomments = $database['count'];

if($newcomments > "0"){
    echo "{\"getnew\":\"{$newcomments}\",\"new\":\"{$now_date}\"}";
}

HTML:

<span id="countcomment" loadtime="2013"></span>

The Error:

Uncaught TypeError: Cannot read property 'getnew' of null 

I don't know what is the problem!

Upvotes: 0

Views: 98

Answers (1)

Rowman Pirce
Rowman Pirce

Reputation: 423

Probably your server sends more data than you expect (e.g. errors). Use the following js code to check response data:

$(document).ready(function () {
  setInterval(function() {
  var lastdate = $("#countcomment").attr("loadtime");
  $.post("update.php",{ajax:"1", lastdate:lastdate},function(data, status, xhr){
     console.log(xhr.responseText)
     },"json");
  }, 1000);
});

Or you can see that data in "Network" tab in Chrome's Developer Tools

Upvotes: 1

Related Questions