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";
});