Jaylen
Jaylen

Reputation: 40371

How to display "loading" icon over a table while waiting for AJAX request to be completed?

I have a page that does an ajax request to the server. the server return "table rows" html code then I place that code into the table.

here is an example of the server answer

<tr>
<td>This is a cell</td>
<td>this is a second cell</td>
<td>this is a third cell</td>
</tr>

In my page when I want to load the results that are coming back fromt here server I have this code

<table id="main">
<tbody id="results">
</tbody>
</table>

this is a example of my jquery

$(function(){
$('#results').html('');
        $.getJSON("ajax/loader-display-previos-calls.php", {
            account_id: <?php echo $account_id; ?>
        },function (data) {

            if ( ! data) 
            return; 
            $('#results').html(data.msg);


            }

        ).done( function(){

            $('.sub_note').shorten({
                moreText: 'read more',
                lessText: 'read less',
                showChars: '100'
            }); 
        });

});

What I am trying to do here is to display a loading icon over the existing table. I am looking to 1) place a transparent block to cover the whole table 2) place a loading icon in the middle of this transparent block.

I have tried this

$('#results').html('<img src="images/ajaxSpinner.gif" alt="please wait..." style="width: 100px; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px;display: block;"/>');

this will display a spinner icon in the center of the page.

basically I sill want to show the current results with a loading icon until the server send back the request.

How can I make the table and it's content transparent then place the loading icon in the center of it?

Upvotes: 7

Views: 19000

Answers (1)

Geoffrey Burdett
Geoffrey Burdett

Reputation: 1976

I think you're looking for ajaxStart() and ajaxComplete()

Add this to your script within:

$(document).ready(function(){
  ajaxStart(){
    $('.mask').addClass('ajax');
  }
  ajaxComplete(){
    $('.mask').removeClass('ajax');
  }
})

And add this HTML tag anywhere:

<div class="mask">

And add this to your CSS:

.mask{
  display: none; /*This hides the mask*/
}

.mask.ajax{
  display: block;
  width: 100%;
  height: 100%;
  position: relative; /*required for z-index*/
  z-index: 1000; /*puts on top of everything*/
  background-image: url (loading-icon.png);
}

Upvotes: 7

Related Questions