1

I am a newbie in php and javascript and am looking for a simple solution how to execute php file from javascript. I stumbled upon several examples (here and here), but they are using jQuery and I want to avoid it.

My intention is to run the update procedure on the server exactly like in the second example.

var stillAlive = setInterval(function () {
    /* XHR back to server
       Example uses jQuery */
    $.get("stillAlive.php");
}, 60000);

I was thinking to use AJAX approach, but all examples are showing how to send and get some data on the request. Here I do not need to send anything, just to execute simple php file. I do not know how to use AJAX this simple plain way.

Thanx for suggestions

Community
  • 1
  • 1
lyborko
  • 2,571
  • 3
  • 26
  • 54
  • 2
    Try looking for a 'vanilla javascript ajax' tutorial like this one https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/ – tristansokol Sep 24 '16 at 14:10
  • _Here I do not need to send anything, just to execute simple php file._ Nevertheless you still need to use AJAX since this is **the only way** to execute script from javascript. – hindmost Sep 24 '16 at 14:11
  • 1
    @hindmost - Not exactly. Since he doesn't want to send or retrieve any data, he could just have a hidden iframe which he reloads in set interval – M. Eriksson Sep 24 '16 at 14:18

2 Answers2

2

This works well by using AJAX (no jQuery required). This script will execute php file every 5 seconds.

<script>
    var exec_php = function () {
      var xhttp = new XMLHttpRequest();
      xhttp.open("GET", "myroutine.php", true);
      xhttp.send();
    }

    setInterval(exec_php, 5000);
</script>
lyborko
  • 2,571
  • 3
  • 26
  • 54
  • 1
    By the way, if the client looses the connection to the server, for lets say 5hours, he will have 3600 opened requests!! It would be better to await the answer, and use a timeout to restart the function – Jonas Wilms Sep 25 '16 at 15:54
1
function set(){
frame=document.createElement("iframe");
frame.src="yourfile.php";
frame.style.opacity=0;
body.appendChild(frame);
frame.onload=function(){
body.removeChild(this);
window.setTimeout(function(){
set();
},2000);
}
set();

This creates a new iframe, if the iframe is loaded, destroy the iframe wait 2 secs and restart the loop.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • thank you for the answer, but I have finally found out, how to run php file by using AJAX. See my answer above. :-) – lyborko Sep 24 '16 at 21:53
  • @lyborko: youre welcome. But as you know, users can earn reputation by getting upvotes etc. Its fair if you would do that :) – Jonas Wilms Sep 25 '16 at 15:52