I attempted to implement an AJAX function but the output is not displaying anything.
var ajaxFunction = function(url, method, data = "") {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && x.status == 200) {
this.responseAjax = this.responseText;
}
}
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
}
function showSuggestion(inputStr) {
var xhttp = new ajaxFunction("gethint.php?q=" + inputStr, "GET");
if (inputStr.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
document.getElementById("txtHint").innerHTML = xhttp.responseAjax;
}
<!DOCTYPE html>
<html>
<body>
<h3> Start typing a name in the input field below :</h3>
<form action="">
First Name : <input type="text" id="txt1" onkeyup="showSuggestion(this.value)">
</form>
<p>Suggestions:
<sapn id="txtHint"></sapn>
</p>
</body>
</html>
I tried to retrieve suggested names from the gethint.php file when a user starts typing into the text box. However, it appears that the value of responseAjax is obtained after the showSuggestion() call. Can someone please assist me?