Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run php script every x mins using ajax request

Tags:

javascript

got this file 'functions.php':

<?php
function test ($url){
$starttime = microtime(true);
$valid = @fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';

if (!$valid) {
   echo "Status - Failure";
} else {
   echo "Status - Success";
}
}
    test('google.com');
?>

I want to run it every 10seconds or so, i was told to use ajax request but i dont completely understand how it works. I tried creating a new file 'index.php', and then had this written in it:

<script>
var milliSeconds = 10000; 
setInterval( function() {
    //Ajax request, i dont know how to write it
    xmlhttp.open("POST","functions.php",true);
    xmlhttp.send();
}, milliSeconds);
</script>

I put both files into ftp but nothing happens, can someone help me write a propper ajax request?

Edit: eddited typo, still doesnt work tho

like image 417
user1894929 Avatar asked May 21 '26 10:05

user1894929


1 Answers

var milliSeconds = 1000;

setInterval( function() {

var xmlhttp;

if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
    xmlhttp=new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}

xmlhttp.onreadystatechange=function()
{
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         console.log ( xmlhttp.responseText );
      } 
}

xmlhttp.open("POST","functions.php",true);
xmlhttp.send();


}, milliSeconds);

You have to load xmlhttp request object according to the browser ( xmlhttp=new XMLHttpRequest(); ), then set an event handler when the xmlhttp state changes ( xmlhttp.onreadystatechange=function() ). When it changes check if the status is 200 (success) then do whatever you want with the response. ( I printed it to console )

like image 184
Glorious Kale Avatar answered May 23 '26 23:05

Glorious Kale