The Javascript Ajax loader gif is malfunctioning

I'm currently working on creating an Ajax loader gif using XMLHttpRequest.

When I type something in the input field, a list of different words appears. This technique is commonly used in search engines as you type in the search box. However, I am also seeing the Ajax loader continuously loading even if I delete the text, which is not the behavior I desire.

What mistake have I made?

Here is the HTML code:

<input type="text" name="input" id="input" />

    <div id='loading' style='display: none'><img src="gifs/ajax-loader.gif" title="Loading" /></div>

    <div id="result"></div>

And here is the Javascript code:

var input = document.getElementById("input");

input.addEventListener("keyup", function () {

    var loader = document.getElementById("loading").style.display = "block";

    var request = new XMLHttpRequest();
    request.open("GET", "ajaxtest.php?data=" + input.value, true);
    request.send();
    request.onreadystatechange = function () {

        if (request.readyState === 4) {
            //loader.src = "gifs/ajax-loader.gif";

            document.getElementById("result").innerHTML = request.responseText;

        }
        if (document.getElementById("input").value === "") {
            document.getElementById("result").innerHTML = "";

        }
    };
    loader.style.display = "none";
});

Answer №1

Start by setting up an event listener to improve how input values are retrieved:

input.addEventListener("keyup change", function () {

You can also incorporate a bit of jQuery code:

$("#loading").hide();
........
if (request.readyState === 4) {
//replace loader.src = "gifs/ajax-loader.gif"; with...
                $("#loading").show();

                document.getElementById("result").innerHTML = request.responseText;

            }
            if (document.getElementById("#input").value === "") {
                document.getElementById("result").innerHTML = "";
           //new code
               $("#loading").hide();
            }
        };
      //replace  loader.style.display = "none"; with ...
        $("#loading").hide();  
    });

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

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

In a production environment, an ENOENT error in Next.js was triggered by fs.readdirSync

Utilizing the Next.js App Router, I attempted to retrieve all my markdown posts stored in files by scanning a directory using fs.readdirSync(). While everything worked flawlessly locally, upon deploying on Vercel, an unexpected issue arose. The code was e ...

jQuery is not active on responsive designs

I have implemented a script in my JavaScript code that changes the color of the navigation bar when scrolling. The navigation bar transitions to a white color as you scroll down. However, I am facing an issue with responsiveness and would like to deactivat ...

What is the optimal approach when incorporating images in HTML?

In the process of developing a Webapp, I am working with PHP and JS on the client side and utilizing MySQL on the backend. I am looking to store images when a new database record is added, such as a profile picture. What are the best practices for this s ...

The toISOString() method is deducting a day from the specified value

One date format in question is as follows: Tue Oct 20 2020 00:00:00 GMT+0100 (Central European Standard Time) After using the method myValue.toISOString();, the resulting date is: 2020-10-19T23:00:00.000Z This output shows a subtraction of one day from ...

Enabling JsTree Checkbox selection according to unique data-id values

I am seeking assistance to automatically check unchecked checkboxes in a jstree based on their data-id values. When the dropdown selection changes, I want to trigger this action. Below are details of my controller and AJAX method. View of my jstree is sho ...

What is a way to ensure that an event is constantly activated when hovering over a specific element?

Currently, I am facing a scenario where I have a button and I need an event to continuously trigger while the button is being hovered. Unfortunately, using the mouseover method only causes the event to fire once when the cursor initially moves over the but ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

Browsing JSON data to pinpoint locations on a Google map

Trying to create a google map using jQuery and javascript with latitude and longitude values stored in a JSON file. Clicking on a state name should generate the map. Encountering an issue where only index[0] is being generated. The for loop seems to be ma ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

Refining a JavaScript array of objects based on account category

Currently, I am facing an issue with filtering a JavaScript array that contains objects with boolean properties based on the user's account type. The goal is to filter out the items that do not apply to the specific account type. I have implemented a ...

Creating a webpage that loads directly to a specific section of content

After searching online, I couldn't find the solution I was looking for. My goal is to have the visible part of the page load halfway down the actual page. This way, when users visit the site, they can immediately scroll up to see more content. I hope ...

PHP Timer for Keeping Track of Time

Is it feasible to develop a timer using PHP that triggers an action after 60 seconds? I am looking for a countdown effect where the timer starts at 60 and decreases to 0. Ideally, I would like to refresh the corresponding div element to simulate the countd ...

Creating a Laravel named route through the use of AJAX within a view

I've been struggling to retrieve data to view, but unfortunately, I'm failing. Can someone lend a helping hand? Below is the code snippet that I'm working with: Route Route::post('/test',array('as'=>'ajaxTest&a ...

Ways to disable the caching feature in Google Chrome

When I am working on CSS and JS around a page, I need to disable the cache mechanism in Google Chrome browser. A trick is to open Chrome DevTools, which automatically disables the cache mechanism (you can configure this in the settings section). Are ther ...

Determine the value of an object by iterating through its keys

UPDATE: (for clarification) I currently have a table named modelCoa +----+----------+-------+--------------------+ | id | id_parent| code | name | +----+----------+-------+--------------------+ | 1 | 0 | 1 | asset ...

Having trouble receiving a JSON array after making an Ajax request

I have read through previous posts on this issue, but I still can't seem to figure it out. Hopefully, someone here can help me solve this problem. My challenge lies in retrieving an array, which I have encoded in json, from a PHP script and passing i ...

"Discover the power of D3.JS with three dazzling charts on a single page, plus a host of additional

As a student, I struggle with English and it makes me feel sorry and anxious... Despite that, I want to create three scatter plot charts on the same page using a single data file (csv). The dataset includes columns for Name, Height, Weight, and Grade (ra ...

Conceal Bootstrap 3 Modal and AngularJS navigation using $location.path

In my AngularJS App, I am utilizing the Bootstrap 3 modal as a dialog confirmation. However, when I hide the modal and redirect, the backdrop of the modal still remains visible. $scope.delete = function () { DataService.delete() .then(function () ...