简体   繁体   中英

reload php code with ajax

I have php code like this :

<div>
<?php if($link AND $access AND !$timer_expired): ?>
<font color="green">Status: Unlocked - You have successfully unlocked "<?php echo htmlspecialchars($link['link_title']);?>", the website is listed below.</font>
<?php else:?>
<font color="red"> Status : Locked - To Unlock "<?php echo htmlspecialchars($link['link_title']);?>" Please Complete the Survey.</font>
<?php endif;?> 
</div>

I need to let it reload it self until the status be "Unlocked" then stop load

There is many of posts talking about reload php file..but i don't need that..i just want to reload php code

Any idea please ?

First of all, if it is PHP page, you'd better to control status on the PHP side. Be independent of client-side. For "Locked" status page set the HTML meta header:

<meta http-equiv="refresh" content="5">

For "Unlocked" status do nothing.

That's all!

It's not totally clear what you're asking, but you need to keep in mind that PHP code is executed on the server. AJAX is executed in the client's browser. So, the way to achieve what you want is to use AJAX to continuously reload the HTML in the client's browser, which you would request from a PHP script on the server.

HTML:

<div id="myDiv">AJAX response will load here</div>

Javascript:

function loadPage(your_page)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
         // This javascript executes when you receive the HTML from your AJAX request
        return xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET",your_page,true);
    xmlhttp.send();

}

var repeat = window.setInterval(checkResponse,3000);

function checkResponse()
{
   var response = loadPage('your_php_script.php');
   if(response.indexOf('Unlocked') !== -1)
       window.clearInterval(repeat);
}

you want to use this function and call ajax like this.

<script type="text/javascript">

 jQuery(document).ready(function() {

  setInterval(function(){

   jQuery("#divid").load('http://example.php',
    function(response, status, xhr) {

        if (status == "error") {
        jQuery("#divid").html(msg + xhr.status + " " + xhr.statusText);
        }
    });
  }, 500);

 });
</script>

You also apply condition to check response is 'Locked' or 'Unlocked'.

Hope it helps to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM