Search code examples
javascriptajaxxmlhttprequest

XMLHttpRequest status returning 404


I have some bit of code from the internet that updates my webpage when I type in a text input.

My code is below

function validate(field, query) {
    var xmlhttp;
    if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
            document.getElementById(field).innerHTML = "Validating..";
        } else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById(field).innerHTML = xmlhttp.responseText;
        } else {
            document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
        }
    }
    xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
    xmlhttp.send();
}

After debugging I found out that the code is run twice (afaik). The first time xmlhttp.readyState is 1, meaning that the request is being set up. The second time it's 4 meaning it's complete. So this is working like intended.

The problem is that it always returns the Error Occurred bit in the field. The reason why is that xmlhttp.status keeps the status number 404, meaning that it is not found. I have no clue why it returns 404. If the browser I'm using is important, I'm using the latest version of Safari. I also checked the latest version of Chrome and got the same problem.


Solution

  • Make sure that your code is actually requesting the correct URL. You can do this with most modern browser's developer tools, including the Network tab of Chrome's.