xhr.send() returns immediately before onload is called
I have a createHTTPClient that calls a URL and after calling the xhr.send(); it immediately returns before the onload/error is called and the response is checked. Is there a way to make the xhr.send() not return until these functions have completed their tasks and I have some data to return? The async flag (true/false) in the xhr.open does not seem to make a difference.
function getData() {
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
...
}
xhr.error = function(e) {
...
}
xhr.open('GET', 'http://www.google.com',true);
xhr.send();
};
5 Answers
-
I tried it, with synchronous method and it seems to work ! :)
function test() { var xhr = Titanium.Network.createHTTPClient(); // open the client xhr.open('POST','http://localhost/somefile.php', false); // send the data xhr.send(data); if (xhr.readyState == 4 && xhr.status == 200){ if (xhr.responseText == '100') { return true; } else { return false; } } else { alert('error'); return false; } } var t = test(); if (t) { alert('ok !'); }
-
I created a custom function send()
when completes it fires an event [http_request_done]
and then you can use the data returnedfunction send(url , event) { var xhr = Titanium.Network.createHTTPClient(); xhr.setTimeout(3000); // Set the timout to 3 seconds xhr.onload = function() { if(this.readyState == 4 && this.status == "200" ) { event.fireEvent("http_request_done", { responseData : this.responseData, responseText : this.responseText }); } else { k.basic.alert("Connection Error","The data couldn't be fetched from the server"); k.log("[K.network.send] [HTTP] - Alert triggerd in the onload"); } }; xhr.onerror = function(e) { k.basic.alert("Connection Error","The data couldn't be fetched from the server"); k.log("[K.network.send] [HTTP] - Alert triggerd in the onerror"); }; xhr.open("GET",url); xhr.send(); }
-
The answer from support is:
Titanium does not currently support synchronous XHR. You just need to kick off the tasks in your onerror or onload.Real nice…NOT!
-
Vannier…THANK YOU SOOOO MUCH!!!
I don't know how much time I've invested to get this to work.
-
maybe use jquery?