Steps for displaying a loading gif animation prior to retrieving text content using JavaScript

Before fetching the PHP result, I want a loading GIF image to display within the div section.

<!DOCTYPE html>
<html>
  <head>
    <title>
      CTR Calculator Tool | Free Click Through Rate Online Calculator
    </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>

  <body>
    <form id="myForm" method="post">
      Clicks: <input name="name" id="name" type="text" /><br />
      Impressions: <input name="email" id="email" type="text" /><br />

      <input
        type="button"
        id="submitFormData"
        onclick="SubmitFormData();"
        value="Submit"
      />
    </form>
    <br />
    Your data will display below..... <br />
    ==============================<br />

    <div id="loader" style="display: none">
      <img src="ajax-loader.gif" />
      <!-- All data will display here  -->
    </div>
    <div id="results"></div>

    <script>
      function SubmitFormData() {
        var name = $("#name").val();
        var email = $("#email").val();

        $.post("submit.php", { name: name, email: email }, function (data) {
          $("#results").html(data);
          $("#myForm")[0].reset();
        });
      }
    </script>
  </body>
</html>

I am trying to implement a loading image before making the server request to fetch results from the PHP file. However, I am facing some challenges in accomplishing this task.

Answer №1

Utilizing JQuery

$("#spinner").fadeIn();
$("#spinner").fadeOut();  

Answer №2

Prior to submitting the form, switch the display style of the div to block. Once the response is received, revert it back to none.

Additional note: It is recommended to convert the current callback function added to the $post method into a promise/async-await format as callbacks can be complex to follow.

 function SubmitFormData() {
        var name = $("#name").val();
        var email = $("#email").val();
        var loader = document.getElementById("loader");
        loader.style.display = "block";  
    $.post("submit.php", {name: name, email: email},
       function(data) {
         $('#results').html(data);
         $('#myForm')[0].reset();
         loader.style.display = "none";
       });
}

//or simply utilize async/await for simplicity

async function SubmitFormData() {
    var name = $("#name").val();
    var email = $("#email").val();
    var loader = document.getElementById("loader");
    loader.style.display = "block";  
    const data = await $.post("submit.php", {name: name, email: email});
    $('#results').html(data);
    $('#myForm')[0].reset();
    loader.style.display = "none";
}

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

Using ThreeJs and TweenJS to insert a delay between tweens using a for loop

Struggling with animating a bin packing problem using Three.JS and Tween.JS. I am having difficulty getting the animation to play successively rather than all at once within my loop. Attempting to use the setTimeout solution has not been successful. Does a ...

Explore a variety of images within an array using Gatsby and Markdown documents

After spending more than 6 hours on this, I've decided to call it quits for today. However, I'm hoping someone out there might have a solution. The problem at hand is as follows: I'm trying to include an array of images in a Markdown file t ...

Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a but ...

`Setting the response as an ArrayBuffer can be achieved on the client side, but it cannot be

I am working on a client-side form where I use XMLHTTPResponse to save response data as a file. In order to achieve this, the response type is set to arraybuffer using the following code: xhr.responseType = "arraybuffer"; While researching various method ...

rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query: I recently received an array from a user which looks like this: userPreferences = [7,5,4] Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object s ...

What could be causing the AngularUI bootstrap datepicker to not appear?

Exploring the popup datepicker demo from angularUI bootstrap, which is embedded in their page and works perfectly. However, when I tried to create a minimal plunker here, the button click does not open the calendar. Any thoughts on what might be causing th ...

Encountering an error in accessing my own API: "Cannot read property 'then

I'm currently in the process of using my personal express.js API with nodejs. Although it is functioning, I am encountering an error that is preventing me from accessing the response of the request. Below is a snippet of my code: routes.js: app.post ...

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

What is the best way to incorporate a subcategory within a string and separate them by commas using Vue.js?

Is it possible to post subcategories in the following format now? Here is the current result: subcategory[] : Healthcare subcategory[] : education However, I would like to have them as a string separated by commas. This is my HTML code: <div id="sub ...

Having several contact forms embedded within a single webpage

I am currently in the process of developing a prototype website and my objective is to have multiple forms on a single page. My goal is to have a form for each service, where users can click on the service and fill out a form to request a quote. The first ...

Steps for initializing input field with pre-existing values using Redux form

After reviewing the Redux Form documentation, I noticed that the example provided only fetches initial values upon button click. However, my requirement is to have these values available immediately when the page loads. In my current setup, I can successf ...

concerns with Ajax-based pagination techniques

I've successfully implemented ajax pagination in codeigniter. However, I am facing an issue where the records are divided by 10 and the page automatically reloads when I click on the next page button. This functionality works fine on localhost but not ...

Custom Jquery function is failing to position divs correctly within ajax-loaded content

I recently coded a custom function that efficiently positions absolute divs within a container by calculating top positions and heights: $.fn.gridB = function() { var o = $(this); //UPDATED from var o = $(this[0]); o.each(function() { var ...

What is the best method to add markup for an ASP button into an ASP page that is stored in a text file?

Is there a way to include ASP markup from a text file on the page? I am integrating the Azure Maps service into our project and need to have an ASP button within a popup displayed on pins. However, I am struggling to achieve this. We currently have a "te ...

Sending Laravel ajax request with ID before selection of options

I am attempting to create a search function using 4 dropdown menus, where each subsequent menu loads data based on the item selected in the previous dropdown. Approach field = Dropdown option Field 1: select A Field 2: options B, C (Select B) Field 3: ...

Issue with Component not displaying properly upon refreshing

I'm currently using react.js and I have a button with an onClick event. My goal is to reload the page after clicking the button and then display a specific component on the page. However, I've encountered an issue where the component doesn't ...

Identifying Changes in ReactJS Pages

As I delve into learning ReactJS, I have been experimenting with various websites that utilize this technology. Presently, my focus is on making an AJAX call to an API based on the URL of a page. The issue arises when clicking a link breaks my code due t ...

Guide to verifying the presence of cookies by name in the browser and granting access to the specific page accordingly

In the process of developing an authorization system with Express, Node, and MySQL, I decided to utilize JWT tokens for user authorization. After successfully storing the JWT token in cookies, my next step is to verify if the token exists in the cookie b ...

Execute the JS function during the first instance of window scrolling

Currently, I have implemented a typewriter effect on my website that triggers when the user scrolls to a specific section. However, I want this effect to occur only once. Unfortunately, every time the user scrolls again (in any direction), the function is ...

Steps on removing a file type from a Material UI textfield

I've been struggling to figure out how to clear a Material UI textfield with type="file" even after trying multiple approaches. My issue arises when I set a file size limit and display an error message if a user tries to upload a file larg ...