AJAX request with JSON return is not responding with my expected behavior

I am attempting to write an ajax call that checks against my database and updates a div if it finds changes.

I’m relatively new to JavaScript, and even more new to JSON things.

I think the problem is in how I am returning the JSON array, or how it is used in the if statement, but I’m not sure how to do it properly. I came to that conclusion based on the fact I get a console log return from the success function “Connected and executed PHP page…”, but NOT the “Updated Tickets Page…” log.

Here is my JavaScript:

function checkUpdates()
{
  $.ajax({
    type: "POST",
    url: 'ajax/checkDB.php',
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
      console.log('Connected and executed PHP page...');
      if (data.hasChanged == true) {
        console.log('Updated Tickets Page...');
        $("#contents").load("dynamic/tickets.php");
        $("#contents").fadeTo("fast", 1);
      }
    }
  });
}

$(document).ready(function() {
  setInterval("checkUpdates()", 3000);  // Calls the function every 3 seconds
});

And here is my PHP (checkDB.php, called in the ajax request), if it matters.

<?php
        include("../static/config.php");
        session_start();

        header("Content-Type: text/json");

        $result = mysqli_query($con,"SELECT notify FROM tickets WHERE notify='0'");
        $row_cnt = mysqli_num_rows($result);

        if($row_cnt > 0) {
            echo json_encode(array('hasChanged' => 'true'));
            mysqli_query($con,"UPDATE tickets SET notify='1' WHERE notify='0'");
        } else {
            echo json_encode(array('hasChanged' => 'false'));
        }


?>

Answer

You are having typo error. You can change either php code without string or change if condition.

//changes made here
if (data.hasChanged == "true") {

PHP

if($row_cnt > 0) {
            //here you are having string "true"
            echo json_encode(array('hasChanged' => 'true'));
            mysqli_query($con,"UPDATE tickets SET notify='1' WHERE notify='0'");
        } else {
            echo json_encode(array('hasChanged' => 'false'));
        }

Leave a Reply

Your email address will not be published. Required fields are marked *