I have been searching and manipulating some xhr ajax things, but I have still not found any solution to this.
What I have is a content loaded in AJAX in jQuery.
What I want to do is to display a percentage loader. I already set beforeSend
with a loading icon, but as I have a lot of data (text), my clients thinks it's stuck...
I already tried this, and this, but it only displays the percentage when everything is already loaded (so it displays 100%
), but that's because the communication between client-server isn't persistent I guess.
Is there a way to do this using PHP and jQuery ? If not, how can I do this ?
Here's my code :
$.ajax({
url: ajax_var.url,
type: 'POST',
data: dataString,
beforeSend: function() {
$("#loader").html("<i class='loading icon'></i> Loading...");
},
success: function(data) {
$("#loaded_data").html(data);
},
error: function(e) {
console.log(e);
}
});
Thanks
Short answer is - no. Long answer is - yes, but only if you do a lot of work and if you understand what goes on behind the scenes.
AJAX works over HTTP, and we know that HTTP is stateless protocol. That means once you ask for something, you get it back. Regardless of it's size. You don't get the response in such a way that you can calculate how much data there is (server has to tell you what the content-length
is).
In other words, whether the response is 1 character or 1TB of data, it's treated the same. You ask for it, until it comes back - you cannot interact with the data. That's why you can't show the progress bar of any kind for a single request, and that's why it only appears once it's 100% loaded. You can display the loading icon and remove it once everything arrives, that's about it.
The solution to this problem lies in performing multiple requests. An example of the workflow would be this:
(Note - the 10KB example serves as an example to explain the principle, it's by no means an advice of any sort to chunk 10kb of data into 10 requests of 1kb each).
The downside of this approach is, of course, that you're stressing the server by issuing multiple requests and that you rely on client side to "assemble" the data into something meaningful.
There are other approaches, but if you require AJAX and plain old jQuery - you don't have many options.