-1

Hi i want to send request in to my php file in every x seconds using ajax how can i achieve this

Here is my ajax code

<script type="text/javascript">
function fun()
{
var exam=new XMLHttpRequest();
exam.onreadystatechange=function()
{
    if(exam.readyState==4)  
    {
        document.getElementById("content").innerHTML=exam.responseText;
    }
}
exam.open("GET","rat_test.php?name=pramod",true);
exam.send(null);
}
</script>

How can i get my goal

Any help will be appreciated

anil kumar
  • 15
  • 1
  • 3
  • 9

5 Answers5

1

It's pretty straightforward:

setInterval(function(){
    //your code here
}, 5000);
Faust
  • 15,130
  • 9
  • 54
  • 111
1

Use setInterval()

In the below example, 5000 represents 5 seconds.

<script type="text/javascript">
    function fun() {
        var exam=new XMLHttpRequest();
        exam.onreadystatechange=function() {
            if(exam.readyState==4) {
                document.getElementById("content").innerHTML=exam.responseText;
            }
        }
        exam.open("GET","rat_test.php?name=pramod",true);
        exam.send(null);
    }
    setInterval(function(){
        fun();
    },5000);
</script>

Resources:

setTimeout or setInterval?

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
0
x = 5; // Seconds
setInterval(fun, x * 1000);

The above code would run the fun function every 5 seconds. The reason we times x by 1000 is because it takes it as milliseconds.

So 1000 = 1 second, 2000 = 2 seconds and so on...

Cameron
  • 51
  • 2
0

you can use this Jquery function :

//x in second 
var sec=x

setInterval(function(){fun()}, x*1000); 
Bouraoui KACEM
  • 821
  • 1
  • 8
  • 20
0

You can use setInterval function

var x = setInterval(function(){
  //Your code
},200); //miliseconds to interval

and if you want to stop it

clearInterval(x);

http://www.w3schools.com/js/js_timing.asp

p1errot
  • 41
  • 1
  • 4