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.

2
  • Asynchronous JavaScript + XML (Ajax) Commented Feb 13, 2016 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. Commented Feb 13, 2016 at 20:45

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you I will try this ! So we have to create a file, otherwise, we can't do a request
Has it been a success?
Almost, I can get the datas but I can't use them outside of the function
I find the answer here stackoverflow.com/a/1639584/4623982 Unfortunately, your solution doesn't works, it is explained why there
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 :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.