When using AJAX, the image may not appear on the initial request but will display on subsequent requests

I encountered a peculiar issue where I am trying to display a loading spinner icon while making an AJAX request. Strangely, the spinner does not appear for the first request (such as after manually refreshing the page) but shows up for all subsequent requests. This happens when the spinner GIF is loaded from a local directory.

Interestingly, when I use this URL (https://i.sstatic.net/FhHRx.gif) that I found on another Stack Overflow post, it works consistently. However, for other URLs sourced from the web or local files, the image fails to show up on the initial request despite the AJAX call being executed (indicated by a change in screen color through styling). Any insights on why this might be happening? Below is the pertinent code snippet.

body

<body>
  ...

  <div class="modal" name="modal" id="modal"></div>

</body>

script

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            $(document)
                .ajaxStart(function () {
                    $("#modal").show();
                })
                .ajaxStop(function () {
                    $("#modal").hide();
                });
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            //Submit Data
            $(".submit").click(function (e) {
                e.preventDefault();

                // get data ...

                $.ajax({
                    url:url,
                    method:'POST',
                    data:{
                        // data values
                    },
                    success:function(response){
                        // update cart and some other stuff
                    },
                });
            });
        });
    </script>

CSS

.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 )
    url('../images/ajax-loader.gif')
    50% 50%
    no-repeat;
}

body.loading .modal {
    overflow: hidden;
}

body.loading .modal {
    display: block;
}

Answer №1

Resolved by embedding the image as a hidden element within the HTML code. It seems like the image was not loading when the request was made via CSS.

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

Dynamic VueJS HTML element selection depending on a condition

While working with Vue JS, I have the capability to do <h1 v-if="someCondition">MY TITLE</h1> Is it possible to determine the element type based on a certain condition? For instance, depending on someCondition, I would like my title to be ei ...

Section of links spanning 4 columns in full-width

Planning to design a 4 column link section for an upcoming website, aiming to achieve the look in the provided screenshot. https://i.sstatic.net/pydBp.png Each box will serve as a clickable link, changing color on hover. Utilizing the Bootstrap framework ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Is it possible for flex-grow to affect images? What steps can I take to identify any issues within my code?

<section> <div class="section-header"> <h5>Discover Our Team</h5> <h1>Meet the Experts</h1> <h5>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt, eaque.</h5> ...

Embedding a picture logo within a CSS-designed content box

I am trying to create a unique layout for my website that reveals content using labelled radio buttons, without the use of scripts. Instead of using <a href='#'>, I want to achieve a specific layout like the one shown in this example. When ...

Add an image to IFromFile in your ASP.NET Core MVC application

I'm looking to allow users to upload images, save them as IFormFile, and then store them in a database. Here's what I have so far: In the product controller, there is only an add action for both get and post methods, the product model, and the a ...

Error message: "When namedPlaceHolder parameter is disabled, bind parameters must be in the form of an

Currently revamping my query due to a crucial API redesign. With the presence of a "file" as multipart/form-data, I found the need for a form handler since NextJS lacked one. After some workarounds with "multiparty", now I can successfully parse the incomi ...

Unable to Modify Header Link Font Color

I've been struggling to change the link color of a header on my website. By default, the link color in my CSS is blue, but I want the links in my entry headers to be gold. I thought this would be a simple task - just define the link color for the hea ...

Selecting a "non-operational" collection location on an e-commerce platform

Recently I discovered a bug on an online shopping website. It seems that by using inspect element, it was possible to alter the HTML code and change an unavailable pickup point to available. This allowed me to place an order, make a payment, and even recei ...

jQuery and HTML: Need help enabling an <input> or <select> element?

Currently, I am using Mozilla Firefox 14.0.1 and Google Chrome 20.0.1132.57 (which I believe is the latest version). The code I am working with looks like this: http://jsfiddle.net/SVtDj/ Here is what I am trying to accomplish: Type something into inpu ...

Transferring extensive PHP variables to JavaScript

After checking out different strategies for passing data from PHP to Javascript like this and this, I have concerns about the memory and variable size limits in javascript. Currently, I am transferring large chunks of HTML from PHP to Javascript to dynami ...

Use Jquery to iterate over the AJAX JSON response and add it to a collection of element identifiers

I have come across some similar inquiries, but none quite fit my needs. Currently, I am utilizing AJAX to obtain real-time updates on property availability. I have successfully received the response and can view it in the console log. However, I am unsure ...

Can JavaScript and CSS be used to dynamically style textarea content as it is being typed by the user?

I am wondering if it is possible to apply styling to content in a textarea as a user inputs text. For instance: <textarea>abcdefghijklmnopqrstuvwxyz</textarea> Is there a way to highlight all the vowels in the textarea string above using jav ...

Guide to aligning MEGA MENU with navbar

I've implemented a navbar that includes dropdown nav-items with a mega menu. The mega menu is set to position:absolute. Is there a way to dynamically align the mega menu in the center of the page while using the same component for all nav-items? Ch ...

Using ng-bind-html within a ng-repeat loop

Currently, I am working on developing a custom autosuggest feature where a web service is queried with a search term to retrieve a list of suggestions that are then displayed. My main obstacle lies in trying to highlight the matching term within the sugges ...

Incorporating Bootstrap content directories into ASP.NET website projects

I've been experimenting with Bootstrap for website design, but I'm facing an issue with adding files to my project. When creating a project in Visual Studio 2015 using File/New/Web Site..., I'm able to simply Copy/Paste the css, fonts, js fo ...

Leverage jquery to adjust the height or width of an element depending on which dimension is larger

I'm a beginner in jquery and html and am currently developing a gallery webpage. The functionality involves setting the selected image as the page background and then scrolling vertically based on the mouse pointer's position. This works well for ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

Using Node.js Express to pass data from both the URL and session into a JavaScript file being served

I've been working on a web-socket application where the client connects to a game instance and the server then links the client to the corresponding Socket.io room for transmitting information. For example, connecting to '/game/abc' would lo ...

Accessing data from another domain using JavaScript with Cross-Origin Resource Sharing (

After researching various CORS and JSON request discussions, I find myself puzzled as to why the first script functions correctly while the second one does not. I am eager to enhance my understanding of CORS, Javascript, XMLHTTPRequest2, and AJAX. The fol ...