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

The function Sequelize.create() does not exist

My attempts to push my DB with sequelize are not working, even though I have set up this schema for the DB: module.exports = (sequelize, DataTypes) => { const Problems = sequelize.define("Posts", { theme: { type: DataTypes.ST ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

The ASP.Net web site is not receiving all required parameters during the AJAX post

Having some trouble with my custom IHttpAsyncHandler and AJAX calls using jQuery. The call is successful, but I'm not seeing the parameters on the server side. This is the AJAX call: function deleteItem(typename) { var data = { "itemType ...

Unfortunately, I am currently unable to showcase the specifics of the items on my website

I am trying to create a functionality where clicking on a product enlarges the image and shows the details of the product as well. While I have successfully implemented the image enlargement, I am facing challenges in displaying the product details. Below ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

"Learn the trick to replace the Ctrl + N shortcut in Firefox and initiate an AJAX request

Note: The answer provided by Juan Mendes has been selected as the best answer for my situation due to its usefulness. AxGryndr also offered valuable information, so I recommend reading both answers as they are beneficial in different scenarios. Thank you t ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Demonstrate the utilization of JQuery to unveil a secondary menu

I need assistance in implementing a sub-menu that automatically appears within 2 seconds after the page loads, instead of requiring user interaction. I am currently utilizing JQuery, which serves as the core framework for my website. It is crucial for this ...

Even after being removed from the DOM using Ajax load, JQuery continues to execute

Currently, within my Laravel 5.2 single page application development, I am faced with the following issue. I have an add.blade.php file and an edit.blade.php file, both containing a script with the same class name and id. When I use .load to load add.blade ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

The component's state consistently reverts to its initial state

I am working with a component called DataGrid that has the following state: const [rows, setRows] = useState([ { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'}, { id: 2, lastName: 'Lanniste ...

What is the process for writing code in a recursive manner?

I'm in the process of converting these code snippets into smaller ones using recursion. However, I've hit a roadblock while trying to implement a for loop. The dictionary I am working with is: var structure = []; and it has the following structu ...

Struggling to connect with PouchDB within my HTML-based Web application

I am looking to integrate pouchDB into my WebApp so that upon clicking a button, the data from a JSON file will be saved to pouchDB. In the initial stage in my index.html, I included the following: <script type="module" src="pouchdb/packa ...

What is the process for running "node server.js" within codelab?

I am currently going through a codelab tutorial on Bitbucket at this link After installing node.js for the first time, I encountered an error when trying to run the server.js file: node server.js The error message "node: Command not found" appeared even ...

Error: JSON data couldn't be processed due to an unexpected end, resulting in a SyntaxError at JSON.parse()

I'm currently working on making an ajax call to an API, but I keep encountering an error whenever I try to make the call. I've been troubleshooting this for hours and I can't seem to figure out what the issue is. At one point, I even removed ...

Is there a way to properly structure the json data displayed in my network tab on Chrome?

After sending an http request to my backend, I received a json response in the network tab. However, the format of the json is unreadable. To clarify, here is a screenshot: https://i.stack.imgur.com/RBiTd.png Currently using Chrome, I am seeking assistanc ...

Utilizing JavaScript in AJAX Responses

Can I include JavaScript in an AJAX response and run it, or should I only use JSON or plain HTML for a more elegant solution? I'm trying to figure out the best way to handle AJAX requests that involve inserting HTML or running JavaScript based on user ...

Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html> <html ng-app="myApp" > <head> <title>myApp.html</title> </head> <body ng-controller="myCtrl as vm"> <br><br> <div> <p> I ...

"Is it possible to rearrange the parent div's position when hovering over a child image with jquery sortable

Can you assist me with a task? I have two text boxes with an equal sign image, and I want the user to be able to move the div only when hovering over the equal sign. This means that the user should be able to drag the div using the equal sign. Can you hel ...

Is there a way to continuously send out this ajax request?

My attempt to use setInterval for sending an AJAX request every 2 seconds is causing the page to crash. It seems like there is something wrong in my code! Check out the code below: var fburl = "http://graph.facebook.com/http://xzenweb.co.uk?callback=?" ...