javascriptphpajax

XHR status 0, readystate 1 on localhost


Working on my own project. I'm sending an XMLHttpRequest to localhost from Firefox 44 to XAMPP. I'm receiving a status of 0 and a readystate of 1. Here's the code in question.

function sendReq(php,segment){
    alert("sendreq called ");
    //we out here getting 0 statuses. check out cwd, check out what php value is,
    xhr.open("POST", php, true);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.onreadystatechange = getData(segment);
    xhr.send(); 
}

//callback function for ajax request.
function getData(div){
    if ((xhr.readyState == 4) && (xhr.status == 200))
    {
        var serverResponse = xhr.responseText;
        div.innerHTML = serverResponse;
    }else{
        div.innerHTML = "<p>loading!</p> ready state: " + xhr.readyState +"</br> status: "+ xhr.status;
    }
}

I've read elsewhere the RS:1 / S:0 XHR properties indicate a unsuccessful cross domain request, but this is all occuring on localhost, with the files all in the same directory, and when inspecting the XHR response in Firebug, the return text is in there.

I've built a login to this page almost identical code and it works, its only pointing to a different .php file. Comparing the two and Googling around are not enlightening me. So any advice is welcome.


Solution

  • You're executing the getData() function once, on pageload, and returning undefined to the onreadystatechange handler, as that's what happens when you add the parentheses.

    It has to be either

    xhr.onreadystatechange = getData;
    

    Note the lack of parentheses, or if you have to pass arguments

    onreadystatechange = function() {
        getData(segment);
    }