Jamie
Jamie

Reputation: 379

Is there a non-ajax way to repeatedly poll an external js file?

would really appreciate any help with this JS question.
Have been experimenting for an hour or so now and haven't bumped into anything that does the trick.


Current Setup


Currently this setup works fine for checking whether a user is logged into website 2 system when a user loads the page on website 1.

However, rather than a once-off check, I'm wanting the PHP file on website 2 to be polled every 2 seconds to see if the loggedin status has changed.

Is there a way to do this in vanilla javascript? (i.e. without ajax or jq - I'm trying to keep the whole system small and known).

If it's relevant, a friend suggested putting a randomly generated variable at the end of the PHP file name to prevent caching. (He didn't know how it could be repeatedly polled though!)

Upvotes: 0

Views: 103

Answers (2)

KooiInc
KooiInc

Reputation: 122956

I suppose you could create an interval function changing the src property of a script element in your page?

setInterval(
  function(){
    myscript.src = '/urltophp?'+someRandomKey;
  }, 2000);

Where someRandomKey prevents the script being cached in the browser. A script tag can have an id, so it's retrievable using document.getElementById

To create a random key this may help:

function randomKey(iLen) {
  var sKey = ''
  , isKey = ''
  , i = 0
  , aRanges = ['48,9', '65,25', '97,25'];
  iLen = !iLen ? 4 : iLen;
  while (i < iLen) {
    var aRange = String(aRanges[Math.round(Math.random() * 2)]).split(',');
    isKey += String(aRanges[Math.round(Math.random() * 2)]) + ',';
    sKey += String.fromCharCode(Math.round(parseInt(aRange[0], 10) +
        (Math.random() * parseInt(aRange[1], 10))));
    i++;
  }
  return sKey;
}

Upvotes: 4

Oliver Bayes-Shelton
Oliver Bayes-Shelton

Reputation: 6292

setInterval(function(){


    $('#divtoloadcontentin').load('urlofscript' + '&nocache=' + Math.random()*Math.random());

}, 5000);

The only reason the divloadcontentin is their is because you could load in a php date() function to show users how up to date the page is.

Upvotes: 0

Related Questions