Skip to content Skip to sidebar Skip to footer

POST To PHP Using AJAX And Refresh Upon Change

I am trying to build a web application that needs to refresh the entire page when there is a change in the database. I would like to achieve this using AJAX and PHP. I would like t

Solution 1:

Good question. You can do if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") { to check if the PHP-side value has changed. This watchdog method is called very 5 seconds through setInterval. If there is a change, then the page is refreshed via document.location.reload(true) (ref) to prevent reusing the cache.

function watchdog() {
  var xmlhttp;
  if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5 - whatever, it doesn't hurt
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {

      // This is how you can discover a server-side change
      if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
        document.location.reload(true); // Don't reuse cache
      }
    }
  };
  xmlhttp.open("POST","page.php",true);
  xmlhttp.send();
}

// Call watchdog() every 5 seconds
setInterval(function(){ watchdog(); }, 5000);

Note: I chose setInterval over setTimeout because if the connection to the server fails (500-error, timeout, etc.), then the response logic may otherwise fail to trigger another setTimeout. setInterval ensures the server is polled consistently regardless of connection failures.


Solution 2:

Your AJAX can be executed every 5 seconds using the setInterval() function. And you can call to refresh the page from AJAX request completion callback.


Solution 3:

Please try below code. I have used javascript setInterval function which will make ajax call every 5 seconds. Now please make efforts to make changes in code as per your requirements and take it further.

<script type="text/javascript" >
    var predefined_val = 'test';// your predefined value.
    $.document(ready(function(){
        setInterval(function(){
            $.ajax({
                type:"POST",
                url:"test/test_script.php", //put relative url here, script which will return php
                data:{}, // if any you would like to post any data
                success:function(response){
                    var data = response; // response data from your php script
                    if(predefined_val !== data){
                        // action you want to perform on value changes.
                    }
                }
            });                     
        },5000);// function will run every 5 seconds
    }));
</script>

Post a Comment for "POST To PHP Using AJAX And Refresh Upon Change"