CodeEnthusiast
CodeEnthusiast

Reputation: 63

How to refresh page display while PHP script runs?

I have a function get_forecast() that retrieves weather forecasts for a city, and then runs that function on an array of cities, and then displays all the results on a single page. What I'd like to do is have the display change to show "Fetching forecast for $city" as the script is retrieving each city's data so I can see the progress, instead of just waiting for the page to load and display the final results.

What would I add to

foreach($cities as $city){

 get_forecast($city);

}

to make it display "Getting forecast for $city" and then refresh the page showing the next "Getting forecast for $city" and then clearing the last one before showing all the forecasts?

Thanks.

Upvotes: 2

Views: 761

Answers (2)

Tim Lytle
Tim Lytle

Reputation: 17624

You are likely not going to find a pure PHP solution to your question because once you output data, you don't really take it back.

Your best bet for this is likely a combination of AJAX and PHP. Use a loop in JavaScript to request the forecasts from a PHP script which only outputs a single forecast. As each forecast is retrieved, using JavaScript to update the content on the page.

I hear jQuery does ajax. That would be a good place to start.

Upvotes: 0

Fosco
Fosco

Reputation: 38526

Do it with Ajax. One call to get the city list, then iterate through them, making a new Ajax request and displaying a status for the user. jQuery is your friend.

Upvotes: 2

Related Questions