0

I would like to know if there is something in JavaScript that loads the contents of a given file.

For example, I have a file called timer.php which (on certain conditions) prints either a 1 or a 0. I need JavaScript to read it and use it as a variable in order to execute a function.

So something like:

function dothis() {

 var timer = getfilecontents(timer.php);

 if(timer == 1) {
   somefunction();
 }
}

And thats pretty much it. Is there anything I can use in the cases like this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • http://en.wikipedia.org/wiki/Ajax_%28programming%29 – Marc B May 05 '14 at 05:30
  • It sounds like you don't actually want the contents of `timer.php`, the contents would be PHP source code. Instead you want to execute `timer.php` on the server and return the result to the browser. – Paul May 05 '14 at 05:34
  • Yes, thats true. I want what timer.php produces. –  May 05 '14 at 05:46
  • Possible duplicate of [Get file contents in java script](https://stackoverflow.com/questions/8103664/get-file-contents-in-java-script) – revo Feb 07 '18 at 10:51

2 Answers2

1

jQuery simplifies AJAX - with jQuery:

function dothis() {
    $.get("timer.php", function(data){
        var timer = data;
        if (timer == 1)
            somefunction();
    });
}
apscience
  • 7,033
  • 11
  • 55
  • 89
  • Thank you, but now when i use a loop like this: setInterval(dothis,10000); it says dothis is not defined. Why? –  May 05 '14 at 06:42
-1

Using the jQuery ajax method you can get the contents of you file.

$.ajax({
    url: "test.html",
    context: document.body
}).done(function() {
    $( this ).addClass( "done" );
});

You can easily get more help about how to use the ajax method from jQuery API document or this URL: https://api.jquery.com/jQuery.ajax/

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Rachit Patel
  • 854
  • 5
  • 12