Question

I am developing a BlackBerry Phonegap application. Therefore, I am using JavaScript.

From a local file, I am trying to fetch some data (bare text) located in the server. I am trying in different browsers (Mozilla and Chrome mainly). The code I am using is as follows:

try{
    request = new XMLHttpRequest();
    request.onreadystatechange = processResults;
    request.open('GET', url, false);
    request.send();
}catch(e){
    alert('exception performing data request: ' + e.name + '; ' + e.message);
}

And the callback:

function processResults(){
    if(request.readyState == 4){    
        if(request.status == 200){
            document.getElementById('divResults').innerHTML = request.responseText;
        }else{
            alert("Error! Status" + request.status + " - " + request.statusText); 
        }
    }
}

The problem I am having is that data is never fetched. The exception returns the following error:

NS_ERROR_FAILURE; Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)

I did some research and the most common cause of these problems is the Same-Origin Policy. However, I am sure to disable it before:

try {  
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");  
} catch (e) {  
    alert("UniversalBrowserRead failed");  
}   

Firebug just points that the error is in the request.send() line, but gives no further information. The xmlHTTP status is 0, although no request.statusText is displayed. What am I doing wrong? Thanks in advance :) .

Was it helpful?

Solution

The solution was to test the application in Internet Explorer, believe it or not. In IE, no error messages appeared and everything worked as expected. After many tests, this is the code that worked for me. Hope it is useful for someone else:

// Create the XHR object.
// For non-IE browsers (Chrome, Mozilla, Opera, Safari, etc.).
if(XMLHttpRequest){
    request = new XMLHttpRequest();
// For IE.
}else if(ActiveXObject){
    try{
        request = new ActiveXObject('Msxml2.XMLHTTP');
    }catch(e){
        request = new ActiveXObject('Microsoft.XMLHTTP');
    }
}else{
    alert('Could not create XMLHTTP request object');
}

// Request the data.
try{
    request.onreadystatechange = function(){
        if(request.readyState == 4 && request.status != 200){
            console.log(request.responseText);
            alert("Error! Status " + request.status + " - " + request.statusText); 
        }
    };
    request.open('GET', targetURL, false);
    request.send();

}catch(e){
    alert('Error while performing the request: ' + e.name + '; ' + e.message);
}

// Empty the content into a proper JavaScript variable.
var text = request.responseText;
var xmlText = eval("(" + text + ")");
// Just fetch the data you want from the xmlText object.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top