PHP на стороне сервера Длинный опрос

Я задавал много вопросов и пробовал много разных вещей (написание и чтение из учебных пособий) относительно длинного опроса по сети, но не получило каких-либо существенных результатов относительно написания php на стороне сервера при попытке провести длинный опрос. У меня настроен клиентский и серверный код. Только у меня есть несколько проблем.

The call doesn't call new records from that last inserted id it calls from 2 weeks ago

Я пробовал много разных вещей, и эти результаты - не то, что я искал.

Все, что мне нужно, это чтобы пользователь вошел в систему, чтобы увидеть все новые сообщения, сделанные друзьями с момента последнего сообщения в фиде. Ajax выбирает последний идентификатор в фиде, который работает отлично. Отправляет это на мой PHP. Я хотел бы, чтобы мой php затем решил, есть ли в базе данных новый пост с более высоким идентификатором, чем текущий, через который он отправил. Отправьте его обратно с помощью JSON и вставьте в ленту новостей. Если у него вообще ничего нет, чтобы потом ничего не публиковать .. У него есть контент для публикации, и новый результат не опубликован. Так что это неправильно. Я подумываю о том, чтобы звонок длился около минуты, а также чтобы остановить обширные звонки на мой сервер.

Я подозреваю, что здесь есть немало людей, которые имеют опыт совершения звонков на сервер, поэтому действительно могу приступить к поиску того, где я облажался. Я думаю, что это сам код PHP, поскольку я не привык использовать циклы JSON и WHILE.

Вот что у меня

AJAX

  $calls = "SELECT  FROM streamdata ORDER BY streamitem_id DESC LIMIT 1";
    $chants = mysqli_query($mysqli, $calls) or die(mysqli_error($mysqli));

    $streamitem_catch = mysqli_fetch_array($chants);
    ?>
    <script type="text/javascript" charset="utf-8">

    function wait() {
        var streamitem_id =<? echo $streamitem_catch['streamitem_id']; ?>;
    $.ajax({
        type: "POST",
        url: "testingajaxfeed.php?streamitem_id=" + streamitem_id,
        async: true,
        cache: false,
    dataType: "json",
    data: { streamitem_id: streamitem_id }, 
        success: function (response){
               $("#homestatusid").prepend("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'><a href='/profile.php?username="+response['username']+"'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><div class'delete' style='cursor:pointer;position:relative;top:0px;float:right;padding-right:5px;' onclick=\"delete_('"+response['streamitem_id']+"');\">X</div><a href='/profile.php?username="+response['username']+"'>"+response['first']+" "+ response['middle']+" "+response['last']+"</a><span class='subtleLink'> said</span><br/><a class='subtleLink' style='font-weight:normal;'>"+response['streamitem_timestamp']+"</a><hr>"+response['streamitem_content']+"<div style='height:20px;' class='post_contextoptions'><div id='streamcomment'><a style='cursor:pointer;' id='commenttoggle_"+response['streamitem_id']+"' onclick=\"toggle_comments('comment_holder_"+response['streamitem_id']+"');clearTimeout(streamloop);swapcommentlabel(this.id);\">Write a comment...</a></div><div id='streamlike'><a title='Like "+response['first']+" "+ response['middle']+" "+response['last']+"s status' id='likecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"likestatus("+response['streamitem_id']+",this.id);\"><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'>Like</a></div><div style='width:50px;' id='likesprint"+response['streamitem_id']+"'><a title='See who likes "+response['first']+" "+ response['middle']+" "+response['last']+"s status' href='include/likes.php?streamitem_id="+response['streamitem_id']+"' /></a></div></div></form></div><div id='streamdislike'><a id='dislikecontext_"+response['streamitem_id']+"' style='cursor:pointer;' onClick=\"dislikestatus("+response['streamitem_id']+",this.id);\"><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'>Dislike</a></div><div style='width:70px;' id='dislikesprint"+response['streamitem_id']+"'></div></div></form><div class='stream_comment_holder' style='display:none;' id='comment_holder_"+response['streamitem_id']+"'><div id='comment_list_"+response['streamitem_id']+"'></div><div class='stream_comment_inputarea'><form id='mycommentform' method='POST'  class='form_statusinput'>\
    <input type='hidden'  name='streamidcontent' id='streamidcontent' value='"+response['streamitem_id']+"'>\
    <input type='input' name='commentingcontents' id='commentingcontents' placeholder='Say something' autocomplete='off'>\
    <input type='submit' id='button' value='Feed'><br/></div></div>");
    {
    return false;
    setTimeout('wait()',1000);
     }
    error: function wait(XMLHttpRequest, textStatus, errorThrown)
    { 
    alert("error: " + textStatus + "(" + errorThrown + ")");   
    setTimeout('wait()',1000);
    }
    }
    });
    }

$(document).ready(function(){

    wait();
});


    </script>

PHP

if (isset($_POST['streamitem_id'])) {
$lastID = $_POST['streamitem_id'];

if(empty($lastID)) {
 die('timeout');
}
else {
$following_string = $_SESSION['id'];
$result="SELECT d.*, c.*, u.*
  FROM streamdata          AS d
  JOIN streamdata_comments AS c ON d.streamitem_id = c.comment_streamitem
  JOIN users               AS u ON u.id = c.comment_poster
 WHERE c.comment_poster = '$following_string'
   AND d.streamitem_id < '$lastID'
   AND (d.streamitem_target  = '$following_string' OR
       d.streamitem_creator = '$following_string')
   OR  d.streamitem_creator IN $friendlist 
   AND d.streamitem_target IN $friendlist
   ORDER BY d.streamitem_id DESC LIMIT 1";
$result = mysqli_query($mysqli, $result) or die(mysqli_error($mysqli));
 while($row = mysqli_fetch_array($result))
    {
        $last_msg_content = $row['streamitem_content']; 
        $last_msg_id = $row['streamitem_id'];
        $last_msg_timestamp = $row['streamitem_timestamp'];
        $last_msg_comment_id = $row['comment_id'];
        $last_msg_comment_content = $row['comment_content'];
        $last_msg_comment_poster = $row['comment_poster'];
        $last_msg_comment_datetime = $row['comment_datetime'];
        $last_msg_comment_streamitem = $row['comment_streamitem'];
        $last_msg_username = $row['username'];
        $last_msg_user_id = $row['id'];
        $last_msg_first = $row['first'];
        $last_msg_middle = $row['middle'];
        $last_msg_last = $row['last'];
    }}}


$response = array();
$response['streamitem_content'] = $last_msg_content;
$response['streamitem_id'] = $last_msg_id;
$response['streamitem_timestamp'] = Agotime($last_msg_timestamp);
$response['comment_id'] = $last_msg_comment_id;
$response['comment_content'] = $last_msg_comment_content;
$response['comment_poster'] = $last_msg_comment_poster;
$response['comment_datetime'] = Agotime($last_msg_comment_datetime);
$response['comment_streamitem'] = $last_msg_comment_streamitem;
$response['username'] = $last_msg_username;
$response['id'] = $last_msg_user_id;
$response['first'] = $last_msg_first;
$response['middle'] = $last_msg_middle;
$response['last'] = $last_msg_last;

echo json_encode($response);

?>

Ответы на вопрос(0)

Ваш ответ на вопрос