Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Ajax implementation using php

I am looking to implement reverse ajax in my application which is using PHP and jquery. I have googled a bit about it and found XAJA but that seems to be a paid application. Is there an open source application available for the same or has someone implemented it?

Some pointers or hints would be very helpful.

Thanks in advance.

like image 562
Ankit Jaiswal Avatar asked Dec 31 '10 06:12

Ankit Jaiswal


2 Answers

I know of two types of reverse AJAX:
1- Polling
2- Pushing

I think polling is rather easier to implement, you just have your javascript make a regular request to the server every time interval, and when the server have some data for it it will respond. Its like a ping and some call it heartbeat, but its the very obvious solution for this problem. However it may easily overload the server.

EDIT Simple polling Example code:
Server-Side:

<?php
//pong.php php isn't my main thing but tried my best!
$obj = new WhatsNew();
$out = "";
if ($obj->getGotNew()){
    $types = new array();
    foreach ($obj->newStuff() as $type)
        {
            $new = array('type' => $type);
            $types[] = $new;
        }

    $out = json_encode($types);
}
else{
    $out = json_encode(array('nothingNew' => true));
}


Client-Side:

function ping(){
    $.ajax(
        {

            url : "pong.php",
            success : function (data){
                data = JSON.parse(data),
                if (data['nothingNew'])
                    return;
                for(var i in data){
                    var type = data[i]['type'];
                    if (type && incomingDataHandlers[type]){
                        incomingDataHandlers[type]();
                    }
                }


        });
}
incomingDataHandlers = {
    comments: function () {
        $.ajax({
            url: "getComments.php",
            method: "GET",
            data: getNewCommentRequsetData() // pass data to the server;
            success : function (data){
                //do something with your new comments
            }
        });
    },
    message: function (){
        $.ajax({
            url: "getMessages.php",
            method: "GET",
            data: getNewMessageRequestData() // pass data to the server;
            success : function (data){
                //do something with your new messages
            }
        });
    }
}
$(docment).ready(function () {
    setInterval(ping, 1000);
})
like image 111
Amjad Masad Avatar answered Nov 14 '22 07:11

Amjad Masad


You are looking for what they call "long poll" - I did a "long poll php" and I got this thread on stack overflow:

How do I implement basic "Long Polling"?

like image 1
Knubo Avatar answered Nov 14 '22 08:11

Knubo