如何检查服务器是否返回undefined然后忽略它

如何检查服务器是否返回undefined然后忽略它

问题描述:

I am sent many dynamic post ids from a page and a php server side page(server.php) make a query with those id to find out newly added data in mysql.

If it not found any newly added data in mysql, it's return a undefined value. So as per my script, It's append a undefined one after one at a time interval.

So how can I check, if php query cannot found anything in sql then exit and not return anything?

I tried this in my php if(mysqli_num_rows($res)) { //do something } but it's also display undefined.

my javascript:

var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});

function addrep(type, msg){
CID.forEach(function(id){
    $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
});
}

function waitForRep(){
    $.ajax({
        type: "GET",
        url: "server.php",
        cache: false,
        data: {CID : CID},
        timeout:15000, 
        success: function(data){ 
            addrep("postreply", data);
            setTimeout(waitForRep, 15000 );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            setTimeout(waitForRep, 15000); }
    });
}

$(document).ready(function(){
    waitForRep();
});

server.php

while (true) {
    if($_REQUEST['CID']){  //cid got all dynamic post id as: 1,2,3,4 etc.
      foreach($_REQUEST['CID'] as $key => $value){

        $datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
        $res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_REQUEST['tutid']."  AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
    $data = array();
        while($rows =  mysqli_fetch_assoc($res)){

          $data[]=$rows;

          $data['id'] = $rows['id']; 
          $data['qazi_id'] = $rows['qazi_id'];
          $data['username'] = $rows['username'];
          $data['description'] = $rows['description'];
          $data['date'] = $rows['date'];
          //etc. all
             $id = $rows['id'];
             $qazi_id = $rows['qazi_id'];
             $username = $rows['username'];
             $description = $rows['description'];
             //etc. all
          } //foreach close
      } //foreach close

          if ($description=="") {$detail .= '';}
            else {$detail .=''.$description.'';}
          $data['detail'] = $detail;
          // do others something more

           if (!empty($data)) {
              echo json_encode($data);
              flush();
              exit(0);
           }

    } //request close
    sleep(5);
} //while close

I tried this in my php if(mysqli_num_rows($res)) { //do something } but it's also display undefined.

I guess that should be because you are calling this php code every 15000 ms via ajax with a setTimeout.

So instead stopping it there you can just ignore it with your js code in addrep() function.

    function addrep(type, msg) {
      CID.forEach(function(id) {
        if (msg.id !== undefined && msg.detail !== undefined) { // <--check undefined here
          $("#newreply" + id).append("<div class='" + type + "" + msg.id + "'>"+
                                     "<ul><div class='cdomment_text'>" + msg.detail +
                                     "</ul></div>");
        }
      });
    }

Or other option is to make use of clearTimeout() when you get undefined.

var timer; // declare the timer here
var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i) {
  CID[i] = $(this).data('post-id');
});

function addrep(type, msg) {
  CID.forEach(function(id) {
    if(msg.id === undefined || msg.details === undefined){
        clearTimeout(timer); // cleartimeout timer
    }else{
        $("#newreply" + id).append("<div class='" + type + "" + msg.id + "'><ul><div class='cdomment_text'>" + msg.detail + "</ul></div>");
    }
  });
}

function waitForRep() {
  $.ajax({
    type: "GET",
    url: "server.php",
    cache: false,
    data: {
      CID: CID
    },
    timeout: 15000,
    success: function(data) {
      addrep("postreply", data);
      timer = setTimeout(waitForRep, 15000); // assign the settimeout to timer
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      setTimeout(waitForRep, 15000);
    }
  });
}

$(document).ready(function() {
  waitForRep();
});