Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a progress bar on $.ajax call

I want to display a progress bar when I click on a button to load content through ajax. As soon as I create the $.ajax call, the communication goes to a php file on the server which scrapes data from another file on the server. And it takes a good 7-8 seconds to bring in the data.

I want to display a progress loader at the time of making the ajax request. I was looking on the internet and couldnt find a simple solution. All I could find were complex upload file scripts which would take an awful while to customize to perform this simple operation. If anybody can help, that'd be great. Else I'd have to make do with the spinner.

like image 941
amit Avatar asked Sep 28 '12 10:09

amit


1 Answers

Because all other answers are just about showing a placeholder image or text or just faking it, here's how you could do it (just a description, no code - but the only hard part is determining how much of the work is actually done):

Edit the php script you call via $.ajax to calculate the percentage of work it has completed - how you would do this is extremely dependend on the tast the script does and as such can be extremely easy (for example, when you're just iterating over an array of things to process which each take about the same time) or extremely hard (e.g. when most of the time is spent in one single, non-repeating call to a library or built-in function). Save this percentage in a session variable:

$_SESSION["PERCENTAGE_DONE"] = $my_calculated_percentage;

Obviously, you want to update this variable as often as is possible and reasonable.

Now, create another php script which just prints out this value (plaintext would be enough for this example, but you could also use json or xml or some other format you like):

//initialize session, set headers etc. before this
echo $_SESSION["PERCENTAGE_DONE"]

For the javascript part, create another function that calls the new php script via ajax, reads the returned value and draws / updates the progress bar (for the drawing part you could take JustinJohns answer as a starting point). Now, after you execute the main $.ajax call, use this function with setTimeout to query the server repeatedly until the task is finished.

like image 197
l4mpi Avatar answered Oct 04 '22 05:10

l4mpi