How can you display a variety of preloader gifs depending on the specific ajax requests being made?

Currently, I have implemented a preloader gif for my ajax requests using the following code snippet:

$(document).ajaxStart(function () {
    var position = $('#parentDiv').position();
    position.left += (($('#parentDiv').width() / 2) - ($('#bigPreloader').width() / 2));
    position.top += (($('#parentDiv').height() / 2) - ($('#bigPreloader').height() / 2));
    $('#bigPreloader').css(position).show();
    $('#bigPreloader').show();
}).ajaxStop(function () {
    $('#bigPreloader').hide();
});

The #parentDiv section occupies most of the page, with the preloader being 250x250 pixels and centered within #parentDiv.

Although this setup works well, I now have additional ajax calls that are related to specific inputs, rather than the entire page. For these instances, I intend to use a smaller preloader (14x14 pixels) placed inside the respective input field itself.

Is there a method within ajaxStart to identify which ajax call was triggered? Alternatively, can multiple ajaxStart events be assigned to specific elements?

SOLUTION

$(document).ajaxSend(function (event, jqxhr, settings) {
    if (settings.url.indexOf('LoadInputData') == -1) {
        var position = $('#parentDiv').position();
        position.left += (($('#parentDiv').width() / 2) - ($('#bigPreloader').width() / 2));
        position.top += (($('#parentDiv').height() / 2) - ($('#bigPreloader').height() / 2));
        $('#bigPreloader').css(position).show();
        $('#bigPreloader').show();
    } else {
        $('#inputLoad').removeClass('notActive').addClass('isActive');
    }
}).ajaxStop(function () {
    if ($('#bigPreloader').is(':visible')) {
        $('#bigPreloader').hide();
    } else {
        $('#inputLoad').removeClass('isActive').addClass('notActive');
    }
});

Answer №1

If all previous calls have finished, the .ajaxStart() function will be triggered. This means that if there are no requests in progress, the code in ajaxStart will be executed. However, when using asynchronous requests, this method may not be very helpful unless all prior requests have completed.

A better solution to address this issue would be to utilize the .ajaxSend() method instead. Unlike .ajaxStart(), this method is fired just before a request is sent out each time. To distinguish between requests, you can examine the parameters passed to the handler function. One approach is to check the URL, as illustrated in this example from the jQuery documentation:

$(document).ajaxSend(function(event, jqxhr, settings) {
    if ( settings.url == "ajax/test.html" ) { //Test by URL
        //Perform specific pre-loader tasks here
    }
});

Additionally, you can specify the context in your specific request. By doing so, the $(this) selector will be set to the specified context, allowing for separation of logic from the DOM. This enables you to have a single function with the loader setup that can be applied to the designated element within the specified context.

$.ajax({
    url: "test.html",
    context: document.body
}).done(function() {
    $(this).addClass("done"); //$(this) refers to document.body or another specified element for the loader.
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to eliminate the initial class with jQuery

I am encountering some issues with removing a class using jQuery. When I open a modal in Bootstrap, it generates code like this: <div class="modal-backdrop fade in"> in the footer. However, when I open a modal within another modal (2 modals), ther ...

Hiding fields based on radio button selection in Prestashop checkout using jQuery

Currently, I have 2 radio buttons and several fields on my checkout page. This is what I want to achieve: - When the "delivery to address" radio button is selected, I want to display fields for address1, postcode, and city while hiding the id_state field. ...

Using jquery mobile to implement an event handler for the close button on a page dialog

Is it possible to trigger a callback before closing a dialog-style page when the close button is clicked? I want to catch and handle the click event of the close button on the dialog page. <div data-role="page" id="page1"> <div data-role="he ...

Discovering the value of an HTML element node in the TinyMCE editor through the use of JavaScript or jQuery

Is there a way to retrieve the node name value using JavaScript or jQuery within the TinyMCE editor? Currently, I am only able to access the nodeName using the code snippet below: var ed = tinyMCE.activeEditor; var errorNode = ed.selection.getNode().node ...

Troubleshooting Owl Carousel: Is it a Shopify problem or a Javascript coding issue?

Having trouble with my owl carousel on Shopify. Can someone check my code for any errors? I followed the instructions but it's not working. Any advice? CSS Styles {{ 'owl.theme.css' | asset_url | stylesheet_tag }} {{ 'owl.carousel.cs ...

Clearing existing HTML content in the TR body

I've been struggling with a Jquery/Ajax call that updates cart details. Currently, I can't seem to clear the existing HTML content in the cart-body (tablebody) even though the ajax request adds all the items to the cart successfully. The code sni ...

Using a CSS wildcard to target intricate IDs

If I had a css selector like #subtab-1, #subtab-2 and so on I could use the wildcard selector as div[id^='subtab-'] But I'm struggling to come up with a wildcard for selectors such as #subtab-1-sub1 #subtab-1-sub2 #subtab-1-sub3 #subtab ...

Creating a visible block in ReactJS: Step-by-step guide

Hello and thank you for all the hard work you do on this platform. I am relatively new to working with ReactJS and have been encountering some difficulties trying to integrate it with sandbox environments like JSFiddle. I have a div element named "app-con ...

Modifying the input type from "Button" to "Submit Button" in order to validate the php form

I require some assistance in switching <input type="button"> to <input type="submit"> in order to easily validate my form using if(isset($name_of_submit_button)){ if(!empty($_POST['input_text_name'])){ ...

Create a unique jQuery script for a gallery that allows you to dynamically pass a CSS class as a parameter

Hey there! I'm a newbie in the world of JavaScript and programming, and I'm struggling to find an efficient solution for a script that assigns parameters to multiple photo galleries. The script is functional, but I believe it can be simplified to ...

Error: foobar is not defined within this scope (anonymous function)

I'm facing an issue with a JavaScript file hosted on a domain called foobar.com. at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", ...

What is the best method for incorporating various fonts in CSS?

Despite being new to the world of coding, I have been exploring ways to enhance the typography on my website. A tutorial I found on W3Schools touches on the usage of CSS for incorporating different font styles across my webpages. Among other things, it exp ...

Safari causing placeholders to be sliced

I'm having trouble creating attractive placeholders in Safari. This is how it currently appears. Codepen: https://codepen.io/anon/pen/RLWrrK https://i.sstatic.net/aChBs.png .form-control { height: 45px; padding: 15px; font-size: 16px; col ...

When using .NET Core Ajax, I kept getting redirected to a JSON response page

While trying to insert data into a database using the .NET Core Framework with AJAX, I was hoping to receive a JSON response upon success. The insertion was successful, but instead of staying on the same page, it redirects me to a page filled with the JSON ...

Display a new div with its content every 5th item

I am currently working with a Smarty template that contains the following code output: Check out my other question on Stackoverflow My problem lies in the fact that the provided code does not repeat the inserted HTML after every 5 elements... Could some ...

Changing the screen resolution can cause the LI elements to become disorganized and appear out of

I have a menu that displays multiple links using a styled UL. Everything looks great at 100% resolution, but when I adjust the screen resolution, the links no longer fit within the menu and some end up on another line, causing issues. My concern is this - ...

How to Retrieve Element Property Values from the DOM with JavaScript

I am currently attempting to access the property of an element within my webpage. My main objective is to toggle a float property between left and right when a specific onClick event occurs. However, despite my efforts, I am facing challenges in even acces ...

Obtain the name of the current view in ASP.NET MVC 5 using Razor on the .cshtml side

As a student who is new to ASP.NET MVC and coming from ASP.NET Web Forms, I am accustomed to it. Here is the list: <ul class="sidebar bg-grayDark"> <li class="active"> <a href="@Url.Action("Index", "Home")"> < ...

Exploring the power of the ReportViewer Control in combination with Ajax Update

Has anyone figured out how to successfully use the Microsoft Report Viewer Control (Web) within an Ajax UpdatePanel? ...

Leveraging Jquery to Unwrap

Looking for assistance with a code snippet that wraps spans in divs. I'm seeking help to unwrap the divs upon pressing another button. You can view a demo of this at http://jsfiddle.net/tonymaloney1971/oh48rafw/4/ Below is the code snippet: $("#Wr ...