user1772519
user1772519

Reputation: 11

Monitor changes on database with AJAX & PHP

i am making a kind of monitor, that shows the changes on database that are created by another web application, i was reloading the page every 10 seconds to show the changes but, i think that is not the "way" to do it, so i was made some research and i found that ajax can do that, calling a function that check that changes, so i wrote my code, but something is missing, so am calling the experts, tha main idea is that when the page are loaded take the id(number) of that last row that was inserted and then saved in a variable called $resultado then call a function called check_changes that do the same query and check the results, if the both variable are equal then no changes, if they are different the reload page.

monitor.php

    <head>
    <script type="text/javascript" src="./js/prototype.js"></script>
    <script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script>
    </head>

    <?
    //code that makes and print the query.

    // here i check the last id(number) and saved on $resultado variable
    $qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
    $qry1=db_query($qry0,$conn);
    while($row=$qry1->fetch_array()) 
    { 
    $resultado=$row['id'];
    }

    //here i call check_changes every 30 seconds
    echo "<script>setTimeout('check_changes()',30);"; 
    //ajax function that check the status of database
    echo "function check_changes(){
    $.ajax({
type: 'POST',
data: {'data':$resultado}, //here am sending the value of result via post
url: './checker.php',   //to checker.php
success: function(data) {
if(data.result==true){ 
window.location = window.location.pathname;
} 
}
})
    }";
    echo "</script>";
    ?>

checker.php

    <?
    $result4 = $_POST['data'];
    include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
    $dbc=connect_db("seguridad");

    // here i check the last id(number) and saved on $result3 variable
    $qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
    $qry1=$dbc->query($qry0);
    while($row=$qry1->fetch_array()) 
    {  
    $result3=$row['id'];
    }

    //here i check if both are equal send false to monitor.php
    if ($result4==$result3){
    $result=false
    echo json_encode($result); 
    }
    else {
    // a new row has been inserted, send true to monitor.php an reload page
    $result=true
    echo json_encode($result); 
    }
    ?>

Upvotes: 1

Views: 2969

Answers (3)

Maulik Shah
Maulik Shah

Reputation: 421

<script type="text/javascript">
var pollTimeout;
var observeChange = {
          'poll' : function() {
              $.ajax({
                   type: "POST",
                   url: 'checker.php',
                   data:"data=<?php echo $resultado; ?>",
                   dataType:"json",
                   async:true,
                   success:function(response){
                        // we have success fully received response,clear the timeout
                       clearTimeout(pollTimeout);                                          
                       observeChange.update(response);                             
                   },
                   error: function(XMLHttpRequest,textStatus){
                        //some error has occured please try after 5 seconds
                        pollTimeout = setTimeout(function()
                        {
                            observeChange.poll();
                        }, 1000);

                    }
                });

          },
          'update' : function(json) {
              //check whether change is there from serever or not if yes than reload page else do poll request again
              if(json.changed=="yes"){
                        window.location.reload();
              }
              else{
                observeChange.poll();
               }
          }
    };
    $(document).ready(function(){
      observeChange.poll();           
    });
    </script>

you can easily do it via comet,it is not advisable to query server for every 10 seconds,you should increase timeout on apache server if you are using apache

suggested apache configurations are

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 240
MaxClients 150
MaxRequestsPerChild 4

checker.php

<?
$result4 = $_POST['data'];
$response=array("changed"=>"no");
include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
$dbc=connect_db("seguridad");

// here i check the last id(number) and saved on $result3 variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=$dbc->query($qry0);
while($row=$qry1->fetch_array()) 
{  
$result3=$row['id'];
}

if ($result4==$result3){
   $response['changed']="yes"; 
}
echo json_encode($response); exit;
?>

Upvotes: 1

sourcecode
sourcecode

Reputation: 1802

in checker.php you are sending data after converting into JSON format ,
but in ajax request you haven't defined the datatype at all,
also if the data coming at ajax success is JSON then you have to parse it first..

        $.ajax({
               type: "GET",
               url: 'checker.php',
               data:{'ata:$resultado},
               dataType:"json",
               success:function(data){
                       if( JSON.parseQuery(data)) //this will run if the result is true.
                         {
                          window.location = window.location.pathname;
                         }            
               }
           });

Upvotes: 0

Michael
Michael

Reputation: 920

You are missing some semicolons in your php-code. I don't think it works at all. You should check for php error messages generated in your postback script.

In your javascript you are comparing the result to a boolean value. The data returned will be a string. This is the correct way, notice the single quotes.

if(data.result=='true'){ 
window.location = window.location.pathname;
}

Upvotes: 0

Related Questions