readyState will not change to 4

1.7k views Asked by At

I am trying to create a dynamic AJAX search bar which communicates with my database. Here is 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 = '';
}

The problem is that the readyState is changing from 0 to 1, but then it will not change to any other state. I need it to change to 4 to enter the function handleSearchSuggest(). I also get this error within the console: TypeError: search.onreadystatechange is null

2

There are 2 answers

0
Drew Noakes On BEST ANSWER

You need to set the callback function correctly.

search.onreadystatechange = handleSearchSuggest;

Note that a ready state of 1 means OPENED and 4 means DONE. You can test this via properties of the XMLHttpRequest class:

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

Try:

search.onreadystatechange = handleSearchSuggest;