Paige Rose Figueira
Paige Rose Figueira

Reputation: 121

javascript if/else statement for JSON data

Attempting to run a scheduled alert with jquery and JSON. The php file works as expected and returns a correctly JSON encoded array. The jquery works and pops up a dialog box every minute when not checking for the JSON data. But when i add in the JSON code, it stops working and nothing happens.

Disclaimer: I know I should no longer be using mysql and should be using prepared statements instead, and I will begin as soon as this project is finished.

EDIT I fixed the typo and changed $getJSON to $.getJSON, and i posted the php script results.

jQuery:

$(function() {

setInterval(function() {

    $.getJSON('includes/popup.php', function(data) {

        if(data.firstName == "None") {

            $("<div>No Callback</div>").dialog();   

        }
        else {

            $("<div>Yes Callback</div>").dialog();

        }

    })

}, 1000 * 60 * 1);

});

popup.php

<?php

$nowdate = date("Y-m-d");
$nowtime = date("H:i");

$alertSql = "SELECT id, compid, cbdate, cbtime, firstName, lastName FROM contacts WHERE  cbdate = '$nowdate' ORDER BY lastName desc";
$alertResult = mysql_query($alertSql, $link);

while($alertRow = mysql_fetch_array($alertResult)){

    $cbtime = date("H:i", strtotime($alertRow['cbtime']));

    if($cbtime == $nowtime) {

        $final_array[] = array("firstName" => $alertRow['firstName'], "lastName" =>                 $alertRow['lastName'], "cbdate" => $alertRow['cbdate'], "cbtime" => $alertRow['cbtime']);

        echo json_encode($final_array);
    }
    else {

        $final_array[] = array("firstName" => "None");

        echo json_encode($final_array);

    }

};

?>

php result:

[{"firstName":"None"}]

 or 

[{"firstName":"Mickey","lastName":"Mouse","cbdate":"2014-09-22","cbtime":"15:36:00"}]

Upvotes: 0

Views: 1076

Answers (3)

user2488184
user2488184

Reputation: 30

you have to convert the json into a javascript object before you use it. Change your code to the below snippet:

$.getJSON('includes/popup.php', function(data) {
  var myobj = jQuery.parseJSON(data);
  if(myobj.firstName == "None") {

    $("<div>No Callback</div>").dialog();   

  }
  else {

    $("<div>Yes Callback</div>").dialog();

  }
})

Upvotes: 0

David Jones
David Jones

Reputation: 4305

This line:

$getJSON('includes/popup.php', function(data) {

Should be;

$.getJSON('includes/popup.php', function(data) {

Upvotes: 2

Paul Roub
Paul Roub

Reputation: 36438

There's a typo:

$getJSON(...)

should be

$.getJSON(...)

The Javascript console should have alerted you to the undefined function.

Upvotes: 2

Related Questions