Goldentoa11
Goldentoa11

Reputation: 1760

HTTP Requests in Phonegap

I have a weird problem with Phonegap. My XMLHttpRequests fire twice; I'm using XMLHttpRequests in an app I'm developing to create a dynamic list of events to select. jQuery is also one of the libs I'm using.

Any time I use an XMLHttpRequest, either vanilla or jQuery, it does it twice, even though it should only run once. Has anyone else ran into this problem?

Some example code here:

(function(){
    var request = new XMLHttpRequest();
    request.open("GET", "http://{site-url-hidden-for-privacy}/events/list", true);
    request.onreadystatechange = function(){
    if(request.readyState == 4){
        if(request.status == 200 || request.status == 0){
            parse_events(JSON.parse( request.responseText ));
        }               
    }
}
request.send();
})();

the XMLHttpResponse text is a JSON array, and parse_events simply takes that array and uses it to create a set of select options for a menu.

Does anyone know why this would fire twice, essentially creating two options for each event, when there should only be one?

Upvotes: 1

Views: 3408

Answers (1)

Goldentoa11
Goldentoa11

Reputation: 1760

Okay, I got it figured out. I was working on this project with a co-worker, and we forgot to listen for the deviceready event to fire, since we're using phonegap. We were binding the "online" and "offline" events when the window loaded, not when the device was ready.

Before:

document.addEventListener("DOMContentLoaded", function(){
    document.addEventListener("online", function(){...}, false);
    document.addEventListener("offline", function(){...}, false);
}, false);

Solution:

document.addEventListener("DOMContentLoaded", function(){
    document.addEventListener("deviceready",function(){
        document.addEventListener("online", function(){...}, false);
        document.addEventListener("offline", function(){...}, false);
    },false);
}, false);

I'm not sure why, as it doesn't make total sense, but I think not going through "deviceready" was causing the HTTP request to go twice, once when the page loaded, and once when the device was ready.

The fix was to make it only go when the device was ready, as shown above.

Upvotes: 4

Related Questions