3

I know that long polling is the best way for making chat updates its contents and i know about web-socket but i think that long polling is best because many browsers doesn't support web-socket . The problem is that i dont know how to write the long polling script , i have an regular ajax and a regular php get and post script , so how can i make this php code and ajax code works in long polling way ? ( i don't want it to keep requesting every second i want it to echo any new messages from the database ... )

here is my ajax code :-

var chat = {}

chat.fetchMessages = function () {
$.ajax({
    url: 'ajax/ajax/chat.php',
    type: 'POST',
    data: { method: 'fetch' },
    success: function(data) {
        $('#chats').html(data);
        $('#chatshere').scrollTop($('#chatshere')[0].scrollHeight);
   }
}); 

}

chat.interval = setInterval(chat.fetchMessages, 1000);
chat.fetchMessages();

and here is my php code :-

<?php
require '../core/init.php';
if(isset($_POST['method']) === true && empty($_POST['method']) === false) {

$chat = new Chat();
$method = trim($_POST['method']);

if($method === 'fetch') {

    $messages = $chat->fetchMessages();

    if(empty($messages) === true) {
        echo 'There is no any messages !';
    }
    else
    {
        foreach($messages as $message) {
        $log_username = $_SESSION['username'];

            if($message['user1'] == $log_username){
            ?>
            <ul class="mychat">
            <li class="first">
            <div class="sOutline">
            <div class="suser">
            <a href="#">
            <img style="height:30px; width:30px;" title="belowfs" alt="belowfs" class="profilepic-belowfs" src="http://demo.scritterscript.com/images/membersprofilepic/thumbs/default-s.jpg">
            </a>
            </div>
            </div>
            </li>                                          
            <li style="margin-left:-5px;">
            <div style="border:1px solid #0099CC; border-radius:5px; background:#0099CC; color:#FFFFFF; padding:7px; max-width:165px;">
            <?php echo nl2br($message['message']); ?>
            </div>
            </li>
            </ul>
            <?php
            }else if($message['user2'] == $log_username){
            ?>
            <ul style="float:right;" class="hischat">
            <li class="first">
            <div class="sOutline">
            <div class="suser">
            <a href="#">
            <img style="height:30px; width:30px;" title="belowfs" alt="belowfs" class="profilepic-belowfs" src="http://demo.scritterscript.com/images/membersprofilepic/thumbs/default-s.jpg">
            </a>
            </div>
            </div>
            </li>                                          
            <li style="margin-right:-5px;">
            <div style="border:1px solid #999; border-radius:5px; background:#999; color:#FFFFFF; padding:7px; max-width:165px;">
            <?php echo nl2br($message['message']); ?>
            </div>
            </li>
            </ul>
            <?php
            }
        }
    }
}
else if($method === 'throw' && isset($_POST['message']) === true) { 
    $message = trim($_POST['message']);
    if(empty($message) === false) {
        $chat->throwMessage($_SESSION['user'], $message);   
    }
}
 }
 ?>

Thanks alot ...

Yassin
  • 1,049
  • 11
  • 15

2 Answers2

2

you might want to do

chat.interval = setInterval(function(){chat.fetchMessages()}, 5000);

instead of

chat.interval = setInterval(chat.fetchMessages, 1000);

for fetching messages every 5 seconds. Rest is up to your PHP code to echo new messages.

Ejaz
  • 8,719
  • 3
  • 34
  • 49
  • thanks for your quick replay , but can you you tell me what this will do ? – Yassin Apr 06 '13 at 12:34
  • will request every 5 seconds. I think i misread your question. Right? – Ejaz Apr 06 '13 at 12:36
  • yeah i want it to be long polling ( only brings the new messages in the database when it is available not just keep requesting like what my code does ) – Yassin Apr 06 '13 at 12:38
  • I think if you're not going to use stream/socket, then what you're doing as an alternate is right. And like it said, you should consider delivering only new messages in your PHP script to reduce network traffic and response size. – Ejaz Apr 06 '13 at 12:41
  • do you mean that i must first bring all the messages from the databse then i check to se if their a new messages available ok , i know how to do it with short polling ajax but how i can do it with long polling ( i want it to see if there is a new messages available ) – Yassin Apr 06 '13 at 12:44
  • for checking new messages, I'd send latest `message_id` in ajax request and, in PHP, only fetch messages newer than that `message_id` – Ejaz Apr 06 '13 at 12:46
  • ok thanks very much , i will do this but how i can do it with long polling ( i read in an article about usleep() and other confusing things and i dont know how to use them ) ... – Yassin Apr 06 '13 at 12:48
  • and if my PHP script doesn't return any message, the UI should assume the conversation as dormant and increase the `setInterval()` duration. Similarly, shorten it if a message is received in a dormant chat. – Ejaz Apr 06 '13 at 12:49
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/27696/discussion-between-ejay-and-magikano) – Ejaz Apr 06 '13 at 12:51
  • i am sorry for the silly question but what do you mean with " he UI should assume the conversation as dormant and increase the setInterval() duration " ( what this will do ? ) – Yassin Apr 06 '13 at 12:51
  • I think this _should_ help you http://stackoverflow.com/questions/333664/simple-long-polling-example-code – Ejaz Apr 06 '13 at 13:20
1

Here is a link where the different methods are clearly explained :

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

The Long-Polling system :

  • A client requests a webpage from a server using regular http (see http above).
  • The requested webpage executes javascript which requests a file from the server.
  • The server does not immediately respond with the requested information but waits until there's new information available.
  • When there's new information available, the server responds with the new information.
  • The client receives the new information and immediately sends another request to the server, re-starting the process.

If there is an interval for the messages to be fetched, you may want to look at the Ajax Polling section.

Community
  • 1
  • 1
Kabylzki
  • 37
  • 7