Friday, 18 October 2013

How to use setInterval and clearInterval jQuery methods in PHP?

How to use setInterval and clearInterval jQuery methods in PHP?

I will explain usage of setInterval and clearInterval jQuery methods with the help of simple example in PHP. Suppose there is a PHP array in which there are 3 elements. I want to display all of them one by one at regular intervals and stop when all the three array elements have been displayed. I will use setInterval and clearInterval jQuery methods here to implement it.

Here is my index.php file

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var count = 0;
$(document).ready(function(){
var auto_refresh = setInterval(function (){
    $('#mydiv').load('myphpfile.php', {count: count}, function () {
        count = count + 1;
        //after three attempts it won't call php file.
        if (count > 2) {
            clearInterval(auto_refresh);
        }
    }).fadeIn("slow");
    }, 1000); 
});
</script>
</head>
<body>
<div id="mydiv"> </div>
</body>
</html>

Here is my myphpfile.php file

<?php
$questions=array(
                 "Array Item 0",
                 "Array Item 1",
                 "Array Item 2");

if (isset($_REQUEST["count"])) 
{
    echo $questions[intval($_REQUEST["count"])];
}
?>

1 comment:

  1. www.easyyar.com is a best jobs site, Search for Job Vacancies IT, Software, Govt., Technical and other jobs.Post your resume now and get your first dream job!

    http://www.easyyar.com

    ReplyDelete