Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery to update a page when a database is modified

Tags:

jquery

ajax

php

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 look 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?

like image 496
Sanks R Avatar asked May 19 '11 05:05

Sanks R


2 Answers

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);
}
like image 64
alex Avatar answered Nov 01 '22 16:11

alex


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.

like image 22
check123 Avatar answered Nov 01 '22 17:11

check123