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

Achieving the selected option's text in Knockout and incorporating it into the URL for an Ajax call

Looking to set up cascading dropdowns where options are loaded from a SharePoint list via AJAX calls. Wondering if there's a way to extract the text of the selected option and use it in another AJAX request URL. Tried referencing this resource: knocko ...

Whenever I repeatedly click the button, the array will store a new value. My goal is for it to collect and store all values obtained from the function

After retrieving data from the listAPI value using an API, the output is displayed as follows: //output - console.log(listAPI) 5) [{…}, {…}, {…}, {…}, {…}] 0: {id: "1", name: "name 1", active: "true"} 1: {id: " ...

Encountering empty parameters in JSP file when they are being transmitted via request

My JSP application allows users to upload files, but they must authenticate using a username and password. In my JSP file, I begin by: //0.2.- We retrieve the password String password = (String) request.getParameter("pass"); // -> This returns NULL //0 ...

Issue: A child component's function is unable to update the state of the parent component

I have been working on a project using React. Below is the code for the parent component: class Parent extends Component { constructor(props) { super(props); this.state = { deleteConfirm: false }; } onDelete = pass => { thi ...

Is it possible to retrieve the complete file path in a form?

My goal is to retrieve a file using an input element of type "file". This element is located within a partial view, and I need to send it to the controller or request it there using "Request.Form["inputFile"];". However, this method only provides me with t ...

Jquery .submit function not functioning properly in Chrome

Currently, I'm diving into the world of ajax. Specifically, I am testing this in Google Chrome. However, instead of displaying an alert saying 'ok' when I click on submit, my browser goes ahead and submits the form automatically. Any ideas o ...

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...

Adjust the size of a div element dynamically to maintain the aspect ratio of a background image while keeping the

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to display images of varying sizes, including both portrait and landscape pictures. These images are displayed as background-image properties of the div. By default, the slider has a fixed ...

An error has occurred: Unable to access the property "filter" as it is undefined

After deploying my react-app online using npm run build, I encountered an issue where a page on my app displayed an error in Container.js. Despite being unfamiliar with this file and its purpose, I attempted to resolve the issue by reinstalling all node_mo ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

Tidying up JQuery with automatic selection of the next div and navigation item

My primary question revolves around optimizing the code for a functionality where clicking on 5 images reveals a related div while hiding the rest. As a newcomer to jQuery, I feel that my current implementation is somewhat messy and lengthy. Seeking advice ...

I am seeking guidance on creating a dynamic search feature using node.js and mongoDb. Any input regarding

I am currently working on implementing a unique feature that involves having an input field on this specific page. This input allows users to perform a live search of employees stored in the database. app.get('/delete' , isLoggedIn , (req , res) ...

What is the best way to make a Dojo TitlePane overlap using CSS?

My dilemma involves a jsfiddle featuring two TitlePane widgets in the central pane's top right corner. Currently, clicking on the right TitlePane ("Switch Basemap") moves the left TitlePane ("Map Overlays") to the left. What I want is for the right Ti ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

Changing the main domain of links with a specific class attribute during an onmousedown event - is it possible?

We are facing a situation where we have numerous webpages on our blog that contain links from one domain (domain1.com) to another domain (domain2.com). In order to avoid manual changes, we are attempting to achieve this without altering the link (href). Th ...

Simultaneously activate the top and bottom stacked components by clicking on them

One of my components has two child components, A and B. Component A is set to position: absolute and placed on top of component B like an overlay. Additionally, component A has a higher z-index. Both components have onClick events attached to them. My que ...

To effectively execute a JQuery / Javascript function, it is essential to incorporate both $(document).ready and $(document).ajaxSucces

I have a JavaScript function that is used for basic UI functionality across my site. Some elements affected by this function are injected via Ajax, while others are static HTML. Currently, I have duplicated the function and applied it to both $(document). ...

Storing the AJAX response in an external variable using jQuery callback function

I'm struggling to set a variable with the results of an ajax query. I understand that I can't just return the result in the success function due to its asynchronous nature. However, I'd like to achieve this using a callback function without ...

Troubleshooting problem with Ajax Calendar Extender

I have a text box where I need to save the chosen date from a calendar. To achieve this, I am using an AJAX calendar extender and setting the target control property to the textbox ID. However, when I click on a button on the same page, I lose the selected ...