In this blog, We are talking about, when an AJAX request is sent to fetch records from the server then it may take time depending on the data processing or the number of records.
If the AJAX request takes more time then at the Client-side there is no visible change is been displayed and the user doesn’t know whether its request is in progress or not.
You can display a loading image or text message on the page when the AJAX request is in progress and hide it after getting a response.
When sending an AJAX call, I’m displaying a loading picture in the demo.
Contents
1. beforeSend and complete
2. ajaxStart() and .ajaxComplete()
3. Conclusion
1. beforeSend and complete
beforeSend
This executes before AJAX request is called
Syntax –
$.ajax({ ... beforeSend: function(){ // Statement } ... });
complete
This executes when the AJAX request is finished whether it successful callback or not.
Syntax –
$.ajax({ ... complete: function(){ // Statement } ... });
Example
When a button is clicked, write a script to perform an AJAX request to search the entered value in a MySQL table.
<script type='text/javascript'> $(document).ready(function(){ $("#but_search").click(function(){ var search = $('#search').val(); $.ajax({ url: '/user/getList', type: 'post', data: {search:search}, beforeSend: function(){ // Show image container $("#loader").show(); }, success: function(response){ $('.response').empty(); $('.response').append(response); }, complete:function(data){ // Hide image container $("#loader").hide(); } }); }); }); </script> <input type='text' id='search'> <input type='button' id='but_search' value='Search'><br/> <!-- Image loader --> <div id='loader' style='display: none;'> <img src='reload.gif' width='32px' height='32px'> </div> <!-- Image loader --> <div class='response'></div>
2. .ajaxStart() and .ajaxComplete()
This is another form which you can use.
- .ajaxStart()
Same as beforeSend
it executes before AJAX request is being sent.
Syntax –
$( selector ). ajaxStart( function() { // Statement });
- .ajaxComplete()
Executes when AJAX request finished same as complete
it also doesn’t depend on whether it’s successful or not.
Syntax –
$( selector ). ajaxComplete( function() { // Statement });
Example
Using ajaxStart
to show the loader image and ajaxComplete
for hiding.
$(document).ajaxStart(function(){ // Show image container $("#loader").show(); }); $(document).ajaxComplete(function(){ // Hide image container $("#loader").hide(); });
3. Conclusion
It is a good idea to show loader on the screen when you are fetching large content from your server. By this, the users know that the request is in progress and wait for completing the request.
You can use any one of the forms (beforeSend, complete or ajaxStart,ajaxComplete) they work the same way.
That’s it.
I hope you guys understand how I can do this. Let me know if you face any difficulties.
You can watch my previous blog here.
Happy Coding {;}