HenioJR
HenioJR

Reputation: 634

XMLHttpRequest with status 0

I'm trying to use XMLHttpRequest, but when I call xmlhttp.send(post), I received xmlhttp with state 1 and status 0. I think that state equals 1 is ok, because mean server connection established, but why status 0? Unfortunately, the other side doesn't receive my request.

function ajaxRequest(method, url, post, callback_fn){
    var xmlhttp;
    if (window.XMLHttpRequest) { //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { //code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open(method,url,true);
    if (method=="POST"){
        xmlhttp.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
        xmlhttp.setRequestHeader("Content-Length", post.length);
    }
    xmlhttp.send(post);
    console.log("xmlhttp.readyState = " + xmlhttp.readyState); // = 1
    console.log("xmlhttp.status = " + xmlhttp.status); // = 0
}

Can someone help me?

Upvotes: 0

Views: 2016

Answers (2)

epascarello
epascarello

Reputation: 207501

Cancel the click and see if it stops the status zero.

onclick="ajaxRequest(...); return false;"

Problem is page is refreshing and killing the Ajax request.

Upvotes: 1

adeneo
adeneo

Reputation: 318182

The onreadystatechange event fires when the state changes, and only when there's a return response can you check what the statusCode of the request was (200, 404 etc.)

function ajaxRequest(method, url, post, callback_fn){
    var xmlhttp;
    if (window.XMLHttpRequest) { //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { //code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            console.log("xmlhttp.status = " + xmlhttp.status);
        }
    }

    xmlhttp.open(method,url,true);
    if (method=="POST"){
        xmlhttp.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
        xmlhttp.setRequestHeader("Content-Length", post.length);
    }
    xmlhttp.send(post);
}

Upvotes: 2

Related Questions