Search code examples
javascriptinternet-explorercross-domainxdomainrequest

Javascript Cross domain requests in IE8


I have a function that verifies an ID against a database. If the ID is found, the function returns true and if not it returns false.

Got the request to work in the other browsers. Now working on figuring it out with Internet Explorer's XDomainRequest.

function verify(id){
    xmlhttp=new window.XDomainRequest();
    xmlhttp.onload = checkResponse;
    xmlhttp.open("GET", "http://abc.com/verify?id=" + encodeURIComponent(id));
    xmlhttp.send();

    function checkResponse(){
        if(xmlhttp.responseText == 200) {   
            return true;
        } else {
            return false;
        }
    }
}

The problem is that I want the verify function to return false, not the checkResponse function.

In other browsers setting the open to false does the trick but not in IE.

No jQuery answers please.

Thanks for your help!


Solution

  • Here is the recommended way to incorporate CORS requests in IE8 into jQuery. You could probably use this as a starting point for your own:

    https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js

    Also, verify shouldn't be a synchronous operation. Would recommend passing a callback function to it and keeping it async:

    function verify(id, callback){
        var xmlhttp = new window.XDomainRequest();
        xmlhttp.onload = function () {
            callback( xmlhttp.responseText === 200 );
        };
        xmlhttp.open("GET", "http://abc.com/verify?id=" + encodeURIComponent(id));
        xmlhttp.send();
    }
    

    Which you could then call like so:

    verify( 123456, function ( isValid ) {
        if ( isValid ) {
            // do something if valid
        } else {
            // or not
        }
    });