Unable to execute php file using XMLHttpRequest

1.1k views Asked by At

I am creating a form, that on a button, calls a javascript file to submit the contents of the form to a php file. My issue is that this works on IE, and will not work on opera, google chrome, or firefox. On analyzing the console in google chrome, I get this error: (Note: I have shortened the localhost path and removed my ip address)

XMLHttpRequest cannot load http://localhost/browse-to-file.php.  No 'Access-Control-Allow-Origin' header is present on requested resource. Origin 'http://internal-ip-address' is therefore not allowed

Also, I have outputted the xmlHttpRequest() status codes as follows:

Ready State: 4
Status: 0

I am testing that the status should be 200.

Is there any easy way to fix this? I am completely lost here.

Edit:

I have found an error in my code, I was calling localhost, when I should have been using the relative path (duh). Now that that is fixed, I am getting another error.

Uncaught TypeError: Cannot set property 'innerHTML' of null
xmlHttp.onreadystatechange

My code is as follows:

xmlHttp = new XMLHttpRequest();

And then the part that is wrong:

  xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4){
    if(xmlHttp.status==200){
        document.getElementById("result").innerHTML=xmlHttp.responseText;          
    } else{
        console.error("Ready State: " + xmlHttp.readyState)
        console.error("Status: " + xmlHttp.status)
        console.error("Status Text: " + xmlHttp.statusText);

        alert("An error has occured making the request")

    }
}
1

There are 1 answers

0
tmaxxcar On BEST ANSWER

The answer was really quite simple. First I had to change the direct page from the 'localhost' to the actual ip address of my server. Then I realized that I was trying to get an Element ID of "result", this was not the correct ID. But it is weird that this did in fact work on IE10.

xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
    document.getElementById("result").innerHTML=xmlHttp.responseText;          
} else{
    console.error("Ready State: " + xmlHttp.readyState)
    console.error("Status: " + xmlHttp.status)
    console.error("Status Text: " + xmlHttp.statusText);

    alert("An error has occured making the request")

}
}

Upon changing the "result" above to the correct id, it works.