Real-time data updates with comets and PHP?

I am going to implement real-time notification updates on my social networking site. I did some research on the comet, and I'm really fascinated by it.

From what I understand, this is the main stream of what is happening on the comet server.

Webpage: Sends an ajax request to server when the document is ready. Server: Queries the database every x amount of seconds and returns a json string containing results if any are found. Webpage: Receives the result of the json string from the server and sends out another ajax request to do the above process again. 

Understanding the comet's work flow, I wrote PHP and Javascript code.

JavaScript code uses the jQuery library and sends an ajax request to the server with the current time in unix timestamp format as a GET parameter.

  $(document).ready(function(){ var timestamp = Math.round(new Date().getTime() / 1000); function comet2(){ $.ajax({ type : 'GET', url : 'comet.activities.php?timestamp=' + timestamp, async : true, cache : false, success : function(data) { alert("current timestamp "+timestamp) var json = JSON.parse(data); if(json !== null){ alert(data); } timestamp = json[0].timestamp; setTimeout('comet2()', 1000); }, error : function(XMLHttpRequest, textstatus, error) { setTimeout('comet2()', 15000); } }); } //call the comet function because the page has loaded. comet2(); }); 

The PHP code will request new actions by searching the database for new lines using timestamp paramater (in this case, the unix timestamp in the request). In this example, I limited the number of results to 1.

 <?php set_time_limit(0); include("models/config.php"); global $mysqli,$db_table_prefix; $last = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0; $results = null; $flag=true; $stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp > ? ORDER BY timestamp DESC LIMIT 0,1"); $stmt->bind_param("i", $last); $stmt->bind_result($id,$timestamp); while($flag){ $stmt -> execute(); while ($row = $stmt->fetch()){ $flag = false; $results[] = array( "id" => $id, "timestamp" => $timestamp ); } $stmt -> close(); usleep(100000); clearstatcache(); } echo json_encode($results); ?> 

The code above does not actually work. The problem is that if the user sends a new comment, he will not be able to add to the database when the comet script is run. This means that the comet script will never return any json result, because the expression in the sql query is never executed (new actions are not added with a newer timestamp). My ajax code for posting new comments works 100%, so I know this is not a problem. Just “nothing happens”, that is - nothing (without errors) is warned or displayed in the browser console.

Change number 3: I'm seriously trying to explain what I mean by “nothing happens”, so I uploaded an image showing that the database insert fails when the comet script is called from jquery (note how the text field is disabled during comment sent via ajax).

enter image description here

What can I do about this? I spent several hours searching the Internet trying to fix this / find a similar working example to no avail.

If I changed the request in my PHP code, follow these steps:

 $stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp **<** ? ORDER BY timestamp DESC LIMIT 0,1"); 

instead:

  $stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp > ? ORDER BY timestamp DESC LIMIT 0,1"); 

warnings are immediately displayed in the browser window, comments can be sent again, and the script is called again and new messages are displayed. This shows that my code "works" fine after completion, and it looks like the request is causing the problem ...

enter image description here

Can anyone see what is going on here? I edited this question 7 times now, and any guide would be great as I just don't get anything.

Just to keep this from closing, here is my question to round up what I discussed above:

Are there more efficient ways to implement a comet server? I am not the most experienced guy, but I would really like to know how to do this. StackOverflow seems to have this feature and it works just fine - how do they do it?

I can’t write my post in more detail than this, and I would REALLY appreciate some of the recommendations from you, amazing people. A suggestion about why my code is “not working” or links to any tutorials explaining how to implement this would be awesome! Thank you in advance and apologize for this monster issue and all the changes!

+4
source share
2 answers

My hunch is that the timestamp value you pass does not produce results. You get the current time through Javascript. Request requests for all messages after this timestamp.

Can you try to print the query and run the same query manually to make sure it is retrieving data from the database?

0
source

So, for the best comet tutorial available for PHP with PHP here. http://www.zeitoun.net/articles/comet_and_php/start

Like if this helps :)

For those who want to use the simple chat solution above in jQuery link, here is the solution.

 <script type="text/javascript"> var Comet = {}; Comet.jquery = { timestamp: 0, url: './backend.php', noerror: true, initialize: function () { }, connect: function () { this.ajax = $.ajax({ type: "get", url: this.url, data: {timestamp: this.timestamp}, success: function (data) { // handle the server response var response = JSON.parse(data); console.log(response); //alert(response.timestamp); Comet.jquery.timestamp = response.timestamp; Comet.jquery.handleResponse(response); Comet.jquery.noerror = true; }, complete: function (data) { // send a new ajax request when this request is finished if (!Comet.jquery.noerror) { // if a connection problem occurs, try to reconnect each 5 seconds setTimeout(function () { Comet.jquery.connect() }, 5000); } else { Comet.jquery.connect(); } Comet.jquery.noerror = false; } }); }, disconnect: function () { }, handleResponse: function (response) { $('#content').append('<div>' + response.msg + '</div>'); }, doRequest: function (request) { $.ajax({ type: "get", url: this.url, data: {'msg': request} }); } } </script> 
0
source

All Articles