Home > Web Front-end > CSS Tutorial > How can I display a loading image during an AJAX request using jQuery?

How can I display a loading image during an AJAX request using jQuery?

Patricia Arquette
Release: 2024-11-21 12:36:11
Original
1041 people have browsed it

How can I display a loading image during an AJAX request using jQuery?

Displaying Loading Image During Ajax Execution

To indicate asynchronous request execution, displaying a loading image is often desired. Let's explore how to achieve this using jQuery's $.ajax method.

Introducing an Image

The desired behavior involves displaying an image to indicate the ongoing request. Here's a simple HTML setup:

<img>
Copy after login

AJAX Request Customization

To augment the $.ajax request with the desired visualization, we must include the following:

  • Show the Loading Image Before Request: Use the fadeIn() or show() method to make the loading image visible.
  • Hide the Loading Image After Completion: Use the fadeOut() or hide() method to remove the loading image after the request finishes.

Customized AJAX Request:

$('#loading-image').fadeIn();
$.ajax({
  url: uri,
  cache: false,
  success: function(html){
    $('.info').append(html);
  },
  complete: function(){
    $('#loading-image').fadeOut();
  }
});
Copy after login

Event-Based Approach

An alternative approach utilizes the global ajaxStart and ajaxStop jQuery events. This allows asynchronous visualization for all AJAX events:

$('#loading-image').bind('ajaxStart', function(){
    $(this).fadeIn();
}).bind('ajaxStop', function(){
    $(this).fadeOut();
});
Copy after login

By implementing these techniques, developers can effectively display a loading image to provide visual feedback during asynchronous requests.

The above is the detailed content of How can I display a loading image during an AJAX request using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template