Search code examples
javascriptxmlhttprequestajax-request

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?


Solution

  • 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.