1

I am populating a js array thanks to php every 2 seconds but it works only the first time because the php code is executed only when I open the window but I want to execute it every time I launch the js function.

Here is my code :

function update(){
    var datas = <?php echo Gallery::getPhotos(); ?>;
    ...
}

setInterval( "update()", 2000 );

The problem is that the var datas never changes because <?php echo Gallery::getPhotos(); ?>; is executed only the first time. How can I do to execute the php every 2 seconds ? I saw solutions with doing a request on a file but I don't know how to do and I don't know if this is the solution for only 1 instruction.

Gallery is a singleton class which stores pictures, the function getPhotos() returns an array with photos names.

oktomus
  • 566
  • 7
  • 28
  • [Asynchronous JavaScript + XML (Ajax)](https://developer.mozilla.org/en-US/docs/AJAX) – Andreas Feb 13 '16 at 18:33
  • While I know AJAX can be used to do this, I couldn't find a SO question that asked this, rather than something about AJAX. If someone else can find a duplicate, please flag. – Roy Falk Feb 13 '16 at 20:45

1 Answers1

1

As the <?php ... ?> is only run on a page load, you may have to use AJAX. Below is a rudimentary example:

EDIT: Heres a working example:

setInterval(function(){
    $.get("myphp.php",function(data){
        update(data);
    });
},5000);

function update(data){
    //...
}

Reference: http://api.jquery.com/jQuery.get/

Matthew Spence
  • 986
  • 2
  • 9
  • 27
  • Thank you I will try this ! So we have to create a file, otherwise, we can't do a request – oktomus Feb 13 '16 at 19:15
  • Has it been a success? – Matthew Spence Feb 13 '16 at 19:55
  • Almost, I can get the datas but I can't use them outside of the function – oktomus Feb 13 '16 at 21:10
  • I find the answer here http://stackoverflow.com/a/1639584/4623982 Unfortunately, your solution doesn't works, it is explained why there – oktomus Feb 13 '16 at 21:26
  • Fair enough, may I ask which answer you used? – Matthew Spence Feb 14 '16 at 13:57
  • I choosed the one on the link – oktomus Feb 15 '16 at 13:00
  • 1
    My solution would work, as we don't return the `$.` (XHR) object. After checking my code, I realise it doesn't wait for a response when returning. Anyways, I assume your retrieval now works. Please note that using a **syncronous** task can cause the browser to lock up when waiting for a response, hence I suggested an **asyncronous** answer above. I have added an edit to my answer with a working (and tested) example of an **ansycronous** catered for you :-) – Matthew Spence Feb 15 '16 at 15:22