The readyState is stubbornly refusing to reach 4

I have been working on developing a dynamic AJAX search bar that interacts with my database. Below is the code I have been using.

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 = '';
}

Currently, I am facing an issue where the readyState changes from 0 to 1, but does not progress to any other state. I need it to reach state 4 in order to trigger the function handleSearchSuggest(). Additionally, I am encountering the following error in the console: TypeError: search.onreadystatechange is null

Answer №1

It is crucial to ensure the callback function is set up correctly.

search.onload = handleSearchRequest;

Remember, a ready state of 1 corresponds to OPENED and 4 corresponds to DONE. You can verify this by checking the properties of the XMLHttpRequest class:

XMLHttpRequest.UNSENT == 0
XMLHttpRequest.OPENED == 1
XMLHttpRequest.HEADERS_RECEIVED == 2
XMLHttpRequest.LOADING == 3
XMLHttpRequest.DONE == 4

Answer №2

Give this a shot:

search.addEventListener("change", handleSearchSuggest);    

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

Transform [object HTMLDocument] to a String

Could someone guide me in converting the newHTMLDocument object into a full string including the doctype and html tag? let newHTMLDocument = document.implementation.createHTMLDocument(); let html = `<!DOCTYPE html> <html> <head> ...

How can I effectively handle extensive data parsing from a file using JavaScript?

Looking to optimize data parsing in JavaScript for a large file? I'm currently using JSON parse for a 250MB file, but it's too slow. Is there a faster method to extract a high volume of data without iterating through every character? The file con ...

achieving bidirectional binding within a directive without using an isolated scope

One of my directives is set up like this: angular.module('somemodule').directive('tooltipText', function ($timeout, $compile, $document, config, $filter) { return { restrict: 'A', scope:{ tooltip: '=&ap ...

What is the best method for extracting span text using selenium?

<p id="line1" class=""><span class="bot">Do you have a short-term memory?</span><span id="snipTextIcon" class="yellow" style="opacity: 1;"></span></p> I want to extract this text: Do you have a short-term memory? This ...

How can I center align my loader inside app-root in Angular2+?

I've successfully added a basic spinner to my <app-root> in the index.html file. This gives the appearance that something is happening behind the scenes while waiting for my app to fully load, rather than showing a blank white page. However, I& ...

Identifying functions that contain dots in their names using JSHint

While running jshint on a JavaScript file, I encountered functions with dots in their names for namespacing purposes. Specifically, within the d3 library, there is a significant portion of code that resembles: d3.select("something") Should I simply disab ...

The request body parser for the express POST method appears to be devoid of

After encountering similar issues on Stack Overflow, I discovered a solution involving the use of: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); However, despite implementing this solution, the log for req.body is still ...

Is there a way to display current data in angularJS based on the current time?

My database contains timestamps like 2016-12-30 00:30:10 which I retrieve using the $http module in Angular. Below is a snippet of my Angular code: angular .module('sampleApp') .controller('ReportCtrl', ReportCtrl) ...

Identify the difference between a regular function and a constructor in JavaScript

How can we determine whether a function in javascript is a simple, plain (anonymous) function, or a constructor (a function with a prototype)? I have developed the following function for this purpose: function checkFunctionType(value) { var ownPropert ...

Working with Ext JS: Dynamically adjusting panel size when the browser window is resized

I am facing an issue with a side panel in Ext.js. Everything is working fine until I resize the browser, at which point some components of the panel get cut off. https://i.sstatic.net/eaEGI.png Is there a way to make the panel resize automatically when t ...

What is the best way to store items in localStorage within Angular version 4.4.6?

I have been working on implementing a basic authentication system in Angular 4.4 with MongoDB as the backend database. login.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from 'app/services/auth.ser ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

I rely on $.ajax to send data using the GET method, but for some reason I am unable to trigger the success callback function even though I successfully receive the data

Feel free to click the body details in order to view the screenshot link. Here is the code screenshot showing an issue where, when using 'post' to send data, Java is unable to retrieve the data as it appears to be 'null' ...

Is it possible for the UUIDs generated by the uuid package to be identical?

I am in need of creating unique UIDs for objects that will be stored in a database. To achieve this, I am utilizing the UUID npm package for generating unique identifiers. I have concerns regarding the possibility of duplicate IDs being generated by this p ...

Trouble with component not refreshing upon store modification in Vuex

Summary: If you prefer, I have a video detailing my issue: https://youtu.be/Qf9Q4zIaox8 Concern with Navbar Component Not Updating on Store Change. The issue I'm facing involves the Navbar component not updating when there is a change in the store. ...

Using console.log as an event listener

Check out this fiddle for reference: http://jsfiddle.net/calvintennant/jBh3A/ I am interested in utilizing console.log as an event listener: badButton.addEventListener('click', console.log); However, the fiddle demonstrates that this approach ...

Encountering an issue when trying to submit the form - "Cannot POST /public/register-controller

I am currently working on developing a login/signup system using Express.js, MySQL, and Node.js. However, I encountered an error when I clicked on the submit button: Cannot POST /public/register-controller This is my index.html: <!DOCTYPE html> ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

Having trouble accessing a JavaScript variable in Javascript due to reading null property 'value'

What I Require I am in need of passing a URL variable from an HTML document to a JavaScript file. HTML Snippet <script> var urlParam = "{{ page_param.asy_request | replace('&','&')}}"; urlParam = urlParam.rep ...