Smithey93
Smithey93

Reputation: 45

Best way to handle large PHP page loading with Jquery/Ajax/HTML etc

Happy New Year, Hope you are well.

I am working on a project which generates a "league table" based on a lot of data, similar to the ones used in various sports (namely football). I have built the backend in PHP which processes the data and outputs the results, however it can take about 6-9 seconds per user, with an average of 10-20 users in a group the page load would take over a minute. To be honest, I expected it to take longer than that as the script has to loop through about 10,000 records per user and do quite a bit of arithmetic.

My question is, what is the best way to load this data into a page? The way I had done it was by having a div the size of the page, on top of all other content, which simply said loading in the middle - this would then make it's self hidden once the page had loaded. This approach was fine but i think it is leaving the door open for various issues - one could be the page timing out or the user thinks it has crashed etc.

What I have been advised to do is have a lightweight page, that calls a api on the server to initiate the request. The api responds with a request id (or something to identify the request anyway), then starts to generate the data. The page would query the api every say 15 seconds to see how its doing, eventually the api would respond saying its complete - then the user would be redirected to view the report.

Any advise/suggestions would be much appreciated.

Thanks in advance,

Smithey.

Upvotes: 0

Views: 1798

Answers (1)

user2629998
user2629998

Reputation:

You should use AJAX to load the data into a div in the page, example code (this code uses jQuery) :

HTML :

<div id="loading"><p>Please wait, loading data...</p></div>
<div id="data"></div>

Javascript :

$(function(){ // This is so that it executes only once the document is loaded
    $("#data").load("/script.php", function(response, status, xhr) {
        if(status == "success") {
            // On success
            $('#loading').hide(); // Hides the "please wait" text
        } else if (status == "error") {
            // Do something on error
            alert("Could not load data, please refresh the page."); // Example alert
        }
    });
});

Upvotes: 1

Related Questions