tiko_2302
tiko_2302

Reputation: 101

xmlhttprequest responsetext is null

I'm trying to make basic HTML Server connection, therfore I want to call and JS function which should call an PHP file just schoing "hello world". Everything is working so far but the response I get seems to be null. I've read through various tutorials but I did not find an answer, hope someone can help me.

            var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status==200 && xhttp.responseText!=null) {
                alert("Responestext: " + xhttp.responseText + "  ENDE");
            }else if(xhttp.status==403){
                alert("forbidden");
            }else if(xhttp.status==404){
                alert("not found");
            }else if(xhttp.responseText==null) {
                alert("response text = null");
            }else{
                alert("Error");
            }
        };
        xhttp.open("GET", "http://URL/fahrgemeinschaft/login.php", true);
        xhttp.send(null);

I expect the output to be "Responsetext: hello world ENDE" but all I get is "Error". I get two alert boxes saying "Error" as well.

Upvotes: 0

Views: 1698

Answers (1)

Alexander O'Mara
Alexander O'Mara

Reputation: 60597

The problem is your onreadystatechange handler is called for every ready state change event, not just when it is done.

You should skip the events that are not done:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState != XMLHttpRequest.DONE) {
        return;
    }
    if (xhttp.status==200 && xhttp.responseText!=null) {
        alert("Responestext: " + xhttp.responseText + "  ENDE");
    }else if(xhttp.status==403){
        alert("forbidden");
    }else if(xhttp.status==404){
        alert("not found");
    }else if(xhttp.responseText==null) {
        alert("response text = null");
    }else{
        alert("Error");
    }
};
xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
xhttp.send(null);

Or to make it easier on yourself, so long as you don't need to support obsolete browsers, just use the onload event.

var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
    if (xhttp.status==200 && xhttp.responseText!=null) {
        alert("Responestext: " + xhttp.responseText + "  ENDE");
    }else if(xhttp.status==403){
        alert("forbidden");
    }else if(xhttp.status==404){
        alert("not found");
    }else if(xhttp.responseText==null) {
        alert("response text = null");
    }else{
        alert("Error");
    }
};
xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
xhttp.send(null);

Upvotes: 1

Related Questions