The function appears to be failing to execute

I'm currently working on a dynamic search bar using AJAX to retrieve results from a database. I've noticed that when I check in the debugger, the code isn't triggering the handleSuggest() function which is responsible for updating the inner HTML of the div where the search results are displayed. Below is the snippet of my code.

function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
    return new XMLHttpRequest();
}
else if (window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
    alert("Your browser does not support our dynamic search");
}
}

var search = getXmlHttpRequestObject();

function ajaxSearch(){
if (search.readyState == 4 || search.readyState == 0){
    var str = escape(document.getElementById('searchBox').value);
    search.open("GET", 'searchSuggest.php?search=' + str, true);
    search.onreadystatechange.handleSearchSuggest();
    search.send(null);
}
}

function handleSearchSuggest(){
    if(search.readyState == 4){
        var ss = document.getElementById('ajaxSearch');
        ss.innerHTML = '';
        var str = search.responseText.split("\n");
        for(i=0; i<str.length-1; i++){
            var suggestion = '<div onmouseover="javascript:suggestOver(this);"';
            suggestion += 'onmouseout="javascript.suggestOut(this);"';
            suggestion += 'onclick="javascript:setSearch(this.innerHTML);"';
            suggestion += 'class="suggestLink">' + str[i] + '<div>';
            ss.innerHTML += suggestion;
        }
    }
}

function suggestOver(divValue){
    divValue.className = "suggestLink";
}

function suggestOut(divValue){
    divValue.className = "suggestLink";
}

function setSearch(x){
    document.getElementById('searchBox').value = x;
    document.getElementById('ajaxSearch').innerHTML = '';
}

Answer №1

There is an issue with the line of code below:

search.onreadystatechange.handleSearchSuggest();

The variable search.onreadystatechange requires a callback function to be assigned to it.

To fix this, update the line to the following:

search.onreadystatechange = handleSearchSuggest;

It is important to note that by making this change, you are not directly calling the handleSearchSuggest function here. Instead, onreadystatechange should point to a callback function rather than its return value.

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

Using JQuery to Retrieve JSON Data from an HTTPS Endpoint

I am attempting to retrieve a JSON file from an https secured website without using server-side languages. The client specifically requested that the process be entirely implemented in JavaScript. After some research, I discovered that I need to utilize J ...

Comparing XDomainRequest and XMLHTTPRequest - which one to choose

Our team is currently developing an application utilizing PixiJS that integrates a dynamic json loader. The .json files are loaded using the following logic: if(window.XDomainRequest) { this.ajaxRequest = new window.XDomainRequest(); } else if (windo ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

A guide on designing a personalized search bar for MUI-Datatables with a sleek outlined style

Check out the default UI from MUI-Datatables v4.3.0 here: https://i.stack.imgur.com/rbHgD.png I want to create a style similar to this: https://i.stack.imgur.com/AUHqC.png Just so you know, I am using the following packages: "@mui/material": &q ...

"ReactJS error: Unable to upload file due to a 400

Every time I attempt to upload a file, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 404". I'm puzzled as to why this is happening. Here's the section of my code that seems to be causing the issue. ...

Is there a way to extract an icon from an object or array?

Currently, I am facing challenges in extracting an icon from either an object or an array for a project I am working on. My approach involves storing the icon in a variable and passing it as a prop to another component. However, the functionality is not wo ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Struggling with web scraping a dynamic website in Python and looking for assistance?

Exploring the world of web scraping, seeking advice for specific situations: Currently working on generating a table of home loans listings by extracting data from Focusing on retrieving values similar to these examples: Homestar Finance | Star Essentia ...

Top method for identifying "abandoned words" within text that has been wrapped

Our content and design teams have a specific request to prevent paragraphs from ending with an "orphan word" - a single word on the last line of text that has wrapped onto multiple lines. The designer's proposed solution is to adjust the margins sligh ...

Using Google Script Code in Sheet to input a key and click on the submission button

Is there a way to enable using the Enter key in addition to clicking the submit button to input data and save it to a cell? I'm having trouble getting my current code to work. Any suggestions on how to modify it? <script> var itemBox = document ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

Update the page by selecting the refresh option from the drop-down menu

In my script, I have different views showing information retrieved from a database. One view displays the quantity of a product sold each month, another shows sales, the third presents profits, and the last exhibits calculated percentages using sales and p ...

Vue instance with non-reactive data

I am looking to store an object in Vue that will be accessible throughout the entire instance but does not need to be reactive. Typically, if I wanted it to be reactive, I would use 'data' like this: new Vue({ data: myObject }) However, since ...

Pinia throws a useStore is not callable error

I have been trying to resolve the issue with (0 , pinia__WEBPACK_IMPORTED_MODULE_1__.useStore) is not a function but unfortunately, I haven't been able to find a solution. Can anyone point out what mistake I am making? Here is my store.js code: im ...

Unable to change the color of InputBase component's placeholder in React.js

I've been attempting to modify the color of the placeholder in an inputbase. I came across several methods online and tried implementing them, but none have been successful. Below are the codes I have tried. <InputBase id="input-id&quo ...

Pause the counter based on the data attribute containing multiple values

I have a collection of div elements, each with a unique data-attribute value. My goal is to display these values in the divs using JavaScript by incrementing a counter. const numbers = document.querySelectorAll(".number"); console.log(numbers); let c ...

Toggle between different socket.io servers for seamless connectivity

I'm looking for help with a situation where I need a socket.io client to connect to server A, disconnect, and then connect to server B. Any ideas on how I can achieve this? Thanks in advance! UPDATE: Attached below is the code snippet that's gi ...

Using input masking to restrict user input to only numbers and English alphabet characters

My input field is masked as "999999999" and functions correctly with an English keyboard. However, I am able to enter Japanese/Chinese characters into it, which breaks the masking. Is there a way to limit input to English keyboard numerics only? <inpu ...

The maximum value of the slider corresponds to the total number of elements in the array

As I work on constructing a Material UI Slider, I have a specific requirement. I want the maximum value of my slider to dynamically adjust according to the number of items in an array of options. ['Answer1', 'Answer2', 'Answer3&ap ...