I attempted to implement an AJAX function, but unfortunately, it is not displaying any output

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?

Answer №1

It's important to handle the AJAX request asynchronously. When you are using the showHint function and trying to set the inner HTML of "txtHint" element with xhttp.responseAjax, you need to be aware that the AJAX call might not have returned yet. This means that the xhttp.responseAjax object is not defined at that moment. To properly handle the response, it's crucial to wait for the response to arrive. One way to do this is by passing a callback function into the ajaxObj definition. The object will call this function once it receives the response.

var ajaxObj = function(url, method, callback, data = "") {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {

            // Handle the response data
            callback(xhr.responseText);
        }
    }
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(data);

}

// The callback function to execute when AJAX finishes
function fillTxtHint(responseHtml)
{
    document.getElementById("txtHint").innerHTML = responseHtml;
}

function showHint(str) {

    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
    }

    // Pass in the callback function to be executed after AJAX returns
    ajaxObj("gethint.php?q=" + str, "GET", fillTxtHint);
}

Answer №2

this within the context of onreadystatechange's handler is actually referring to an instance of XMLHttpRequest, hence the line

this.responseAjax = this.responseText
seems redundant as it creates a field in the object that already exists and sets its value to another existing field. In the function showHint, the variable xhttp represents an instance of ajaxObj, however there is no pre-existing responseAjax field defined for this particular object. Instead, you can directly manipulate the innerHTML property of the element displaying suggestions inside the event handler of onreadystatechange like below:

function getSuggestions (method, data) {
    method = method.toUpperCase();
    var params = "q=" + data;
    var url = (method == "GET") ? "gethint.php?" + params : "gethint.php";

    var elem = document.getElementById("txtHint");

    if (data.length == 0) {
        elem.innerHTML = "";
        return;
    }

    var x = new XMLHttpRequest();

    x.onreadystatechange = function() {
        if (x.readyState == 4 && x.status == 200) {
            elem.innerHTML = this.responseText;
        }
    }
    x.open(method, url, true);
    x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    if (method == "GET") { 
        x.send(); 
    } else { 
        x.send(params); 
    }

}

Then, the modified showHint function will look like:

function showHint(str) {
    getSuggestions ("GET", str);
}

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

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

How can I delete an item from an array when I click on a selected element using Material React Select Multiple?

I found this helpful CodeSandBox demonstration that walks through how to implement a multiple material select feature. Here is an array containing all the available options: const permissionsGroupList = [ { name: 'Sellers' }, { name: &a ...

loop through an array and use splice to select items and modify the array

My current issue involves working with a pixabay array. Although I successfully retrieved the data from my array, it contains 20 random pictures when I only need 3 to be displayed on my website. I attempted to use a slice array for this purpose, but unfor ...

Tips for executing a jQuery nested template in a recursive manner

Imagine a world where JSON objects and jQuery templating collide in a thought-provoking inception-like scenario. How can we dive deeper into this rabbit hole? The catch is, I'm a bit lazy and hoping the code will do most of the heavy lifting... Q:> ...

I am unable to select the first item when using select2.js and setting a placeholder

I am experiencing an issue with my <select> list that is styled using select2.js. Everything seems to be functioning properly, except for when a placeholder is used. Users are unable to select the first item in the list initially. If they choose any ...

Tips for preventing directly mutating a prop within a recursive component

The child operates on its own copy of the prop data and can notify the parent using `$emit` when a change occurs. Imagine dealing with a recursive tree structure, like a file system for example: [ { type: 'dir', name: 'music', childr ...

XMLHttpRequest Refusing to Send Data

This snippet of code is crucial for the custom extension: let url = "https://mywebsite.com/data.php"; function sendRequest() { var client = new XMLHttpRequest(); client.open("POST", url, true); client.setRequestHeader("Content-Type", "text/pla ...

A guide to incorporating nested loops with the map method in React JS

I've come across numerous threads addressing the nested loop using map in React JS issue, but I'm still struggling to implement it in my code. Despite multiple attempts, I keep encountering errors. Here are some topics I've explored but cou ...

I seem to be having trouble using my markers on my istamap

function initialize() { var mapProp = { center:new google.maps.LatLng(51.508742,-0.120850), zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new ...

Continue iterating using (forEach, map,...) until the object (children) has no more elements

I need to disable the active status for all elements within my object structure. Here is an example of my object: const obj = { name: 'obj1' , ative: true , children: [ { name: 'obj2' , ative: true , children: ...

Please ensure that all files have finished downloading before proceeding to create the object

Within my Session class, I've been instantiating objects from my Question Class. Within this process, images are being downloaded to a local path. However, the issue arises when my LaTeXDoc class demands that all images are already saved at the time o ...

Initiate a follow-up function once the initial one has been finished

I'm experiencing some issues with jQuery and AJAX. I have 2 functions that perform AJAX calls: Function 1: getSelectedRoom($chosenRoom) and Function 2: getDeviceTable("all", "div#DeviceTables",0,1,1,0,1,$chosenRoom) The first func ...

Is it possible to generate a component dynamically using a string template?

I have a Component called "CDataTable" that renders columns in a for loop. Inside the loop, there is a template: <template v-if="typeof col.template !== 'undefined'" #body="{data}"> <component :is="compile(co ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...

Is it possible to set up multiple registries within a single package.json configuration?

Is it possible to define two different registries within the publishConfig section of the package.json file? The scenario is that we want to publish the artifact to two different locations depending on its purpose. For SNAPSHOT versions, we would like to ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

When a property is passed as a prop in a Vue component, it is received

https://jsfiddle.net/2xwo87bs/ In order for Vue to properly handle the object prop that is being passed to the component, it is necessary to first convert the string into an actual object. While in the provided snippet I have used JSON.parse() as a qui ...

Encountering an AJAX issue while attempting to retrieve data

I've encountered a persistent issue with errors in my ajax call from jQuery, specifically within the index.php program. Even after attempting to simplify the problem, I am still facing the same error. Below is the code snippet from index.php: <scr ...

Avoiding the unnecessary re-rendering of input fields in React when their values change

I am developing a form that is dynamically generated using JSON data fetched from an API. The JSON structure includes information about the input elements to be rendered, such as name, type, placeholder, validation rules, and more. { name: { elemen ...