I want to update a page when my database is modified. I want to use jquery for doing this. Question not clear? Then have a lo开发者_开发技巧ok at this, Suppose this is my page:
<?php
$query=mysql_query("select * from tbl1 where user='admin'");
if(mysql_num_rows?($query)!=0)
{
echo 'Table 1 has values';
} else {
echo 'Table1 is empty';
}
?>
This action should be performed whenever any new entry is added to the database. Now suppose I add an entry to the database manually then the page should automatically show the result as "Table1 has values". I know it can be used by using refresh page periodically but I don't want to use it. Instead I want to try something other, like ajax polling? Can someone give me a demo?
You can use long polling, but do a lot of research first. Your server may kill the request that appears to be open for a long amount of time.
In PHP, your code will look something like...
set_time_limit(0);
while (TRUE) {
// Query database here
if ($results) {
echo json_encode($results);
exit;
}
sleep(1);
}
You can use Ajax jQuery Framework with Ajax:
http://www.w3schools.com/Ajax/default.asp
http://api.jquery.com/jQuery.ajax/
It will call the server side script Asynchronously and update your page accordingly. You can use jQuery to specify the format of the update also.
You are looking for Ajax-Push/Comet solutions. These aren't trivial.
You also mentioned ajax pooling.
Well, on the server side you need to loop until you have a timeout (that you defined yourself or the server did, make sure you return the HTTP status code for Timeout Occured) or the request can be satisfied.
And on the client side whenever you complete the operation successfully just handle it and than make the same ajax call again, if you timed out just make the same ajax request again until it's satisfied.
精彩评论