Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Android XHR: onload and onerror not firing (works fine on iPhone)

This one's driving me a bit crazy. I have some simple xhr code that fails to throw either onload or onerror events on Android.

The code does make the HTTP call, but doesn't execute the onload and onerror functions: neither SUCCESS nor ERROR are printed to the log.

The same code works perfectly well on iPhone.

I suspect this has something to do with the context the code is running in; I've had similar issues with other events not firing on Android that were resolved by moving the events to other windows or contexts.

This code was previously working. I cleaned various things up to encapsulate things, put them into separate windows, and at some point this quietly broke.

Ideas are appreciated.

var httpRequest = Ti.Network.createHTTPClient();
httpRequest.open("GET",  "http://parand.com/");
httpRequest.onload =function(xhr) { Titanium.API.info('=== SUCCESS'); }
httpRequest.onerror =function(xhr) { Titanium.API.info('=== ERRORR'); }
httpRequest.send();
Titanium.API.info('--- HTTP REQUEST SENT');
— asked October 10th 2011 by Parand Darugar
  • android
  • httpclient
  • iphone
  • mobile
  • xhr
0 Comments

2 Answers

  • What happens if you try setting the onload and onerror before the open()

    — answered October 10th 2011 by Kosso
    permalink
    0 Comments
  • Figured out the issue: I was closing the window that was doing the XHR call before the call was completed. This, apparently, is fine under iPhone, but causes problems under Android.

    I ended up moving the XHR call to an async thread (via code below), separating the window lifetime from the XHR lifetime.

    var asyncThread = Ti.UI.createWindow ({ url: "async.js" });
    asyncThread.open();
    
    — answered October 10th 2011 by Parand Darugar
    permalink
    2 Comments
    • although this worked, probably not a very good pattern to use for your applications. I would recommend either a single context application or using an event to close the window based on the success or failure of the http request

      — commented October 10th 2011 by Aaron Saunders
    • Aaron, much thanks for that. I thought this was the recommended way of doing background tasks?

      It turns out I can do most of what I need via events instead of having a separate async window - I guess you're saying it's worthwhile turning everything into events?

      — commented October 10th 2011 by Parand Darugar
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.