Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue.

I've been trying to use the click() and load() functions to bring my content into a specific CSS class.


$("#feed").click(function(){
      $(".homefeed").load("feedcontainer.php");
          $("#elementcontainer").show();
      });

      $("#news").click(function(){
      $(".homefeed").load("n.php"); 
      $("#elementcontainer").show();
      });

       $("#info").click(function(){
      $(".homefeed").load("newinfo.php");
      $("#elementcontainer").hide();
});

So basically, whenever I click on a div, it loads the content from a PHP file into the .homefeed container as intended.

The only thing is, I'd like to add a loading image or animation while the content is being loaded, just to keep users engaged. Because sometimes it takes a bit of time to load, you know?

Any ideas on how I can make this happen? Much appreciated!

Answer №1

Here is a suggestion:

$(".homefeed").prepend(response);
can be changed to $(".homefeed").html(response)

$("#info").click(function (e) {
$("#loadimg").show(); 
jQuery.ajax({
            type: "POST", 
            url: "newinfo.php", 
            dataType:"text", 
           cache: true,
            success:function(response){
                $(".homefeed").html(response);
                $("#loadimg").hide();  
            },
            });
    });

Answer №2

One solution to consider is incorporating the jquery blockUI plugin into your project. Take a look at this helpful resource: jquery blockUI

Answer №3

To incorporate a loading animation before an AJAX call in jQuery, utilize the .beforeSend option. It's important to note that this method only functions with asynchronous AJAX calls. If you attempt to use it with synchronous calls, no animations or callbacks will be executed as jQuery is busy blocking everything until the call returns.

$.ajax({
  url: "http://myurl.dot.com.jpeg.image.file.chmtl.php.asp.cfm",
  async:false,
  cache: false,
  beforeSend: function( xhr ) {
    // Implement loading animation here
    // (such as displaying a dialog or showing a spinner)
  },
  done: function(data){
    // Process response data here
  }
})

http://api.jquery.com/jquery.ajax/

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

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Tips for automatically activating the HTML select menu on an iPad

My website features a suburb lookup tool that allows users to input a suburb or postcode (Australian only, e.g. 4000, 2000, Brisbane, Sydney etc) and receive the corresponding suburb/state/postcode in a select menu format: <select size="4" name="contac ...

Guide to positioning a div in the center while implementing animations through transition and transformation using scale

Creating a popup for my React app without relying on external libraries is my current project. I am experimenting with using transition and transform with scale to size the popup dynamically based on screen size and content, then center it on the screen. ...

validating links in Laravel

Is it feasible to validate a href element in laravel? For instance, I have various user responses in my guest book and each user has the capability to delete their posts. The deletion process is as follows: <div class="col-lg-2"> <ul class="l ...

Is there a way for me to insert a hook into the DOM after a promise has finished updating

Currently, I am tasked with maintaining a code snippet that resembles the following structure: {#await details} {#each values as value, i} <td id="{`${config.id}_${i}`}">{value}</td> {/each} {:then details_result} {#each de ...

Toggle the input box by clicking the button

How do I show or hide the input box (blue square) when I click the search button (red square)? Link Image I attempted to create the transition in CSS and also experimented with JavaScript, but the JavaScript part confused me. Here is what I tried: $(" ...

Lightbox2 is looking to reposition the caption to the right of the image

Can anyone help me understand how to move the caption, found in data-title, from underneath an image to the right of the image? I'm not very familiar with HTML/CSS, but it looks like the image is enclosed within a div called .lb-outerContainer, and t ...

Display HTML content within a Material-UI Card component using React

Currently, I am utilizing the < CardHeader /> component nested within a < Card />. <CardHeader title={card.title} subheader={`${moment(card.createdAt).startOf('minute').fromNow()}` + ' by ' + <div>ABC</div>}/ ...

Is it possible to obscure the PHP file path and conceal the parameters in a POST request?

Is there a way to securely increase the liking number on records in a database without exposing sensitive information through post requests? The PHP file and GET parameters are visible in the post request, allowing anyone viewing the page source to poten ...

Axios and Postman generate unique X-CSRF tokens

Why does the X-CSRF token I receive from my axios request differ from the one I get in Postman? Here is how I am retrieving it: headers: { "X-CSRF-Token": "FETCH" } Furthermore, I am unable to use the X-CSRF token from my axios request in Postman as it ...

Choose a specific 24-hour range with the Date Interval Selector

I am currently utilizing the Date Range Picker plugin for bootstrap from the website http://www.daterangepicker.com/#examples, and I have a requirement to set the maximum date time range to be within 24 hours. Below is an example demonstrating how I can s ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

Consistent word spacing across several lines

Can someone help me with an issue I'm facing? It seems simple, but I can't seem to figure it out. I am looking for a way to maintain consistent spacing between words on multiple lines without using tables. Essentially, I want something like invi ...

Guide on adjusting the language settings for notifications in chosen.js?

Is it possible to customize the error message that appears in chosen.js when an unavailable option is typed into the multiple select box, which currently says 'No results match "query"'? ...

Creating dynamic URLs with jQuery

Trying to create a link with a dynamic URL that queries a service. Here is the code snippet: var link = $("#id").text(); $('<a href="#" id="testselect">button</a>').insertAfter("#searchtextselecttest"); $("#testselect").attr('h ...

Using vuetify's v-autocomplete component with the options to select all and clear items

I am trying to incorporate a "Filter by values" feature in my application similar to Excel or spreadsheets. However, I am facing difficulty with implementing the 'Select all' and 'Clear' button in v-autocomplete. <v-col> < ...

Create a distributive and an NPM package using one source code

Creating small open source tools is a passion of mine, and I strive to provide the best experience for my users. My packages usually consist of just one function, so here's what I aim to offer: A JavaScript file that users can easily add by including ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...