0

I'm building this code to calla web service. Now I want that this method return an object.

So this is the command that call the method:

Titanium.API.info("CHIAMO IL WS CON DATA NULL");
getDocument("CFDECTEST02",null, function(obj) {
   Titanium.API.info("CALL BACK CHIAMATA "+ obj);
});

This is the method that call web service:

function getDocument(fiscalCode, date){
    var obj;
    var xhr = Titanium.Network.createHTTPClient();
    xhr.setTimeout(10000);
    xhr.open('POST', "http://url");

    xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    var myObject = {
         cf :fiscalCode,
         date_last_synchronization :date 
    };
    xhr.send(JSON.stringify(myObject));

    xhr.onerror = function() {
        Ti.API.info("SERVIZIO IN ERRORE");
        Ti.API.info(this.responseText);
        disattivaSemaforo();
    };
   xhr.onload = function() {
        var obj = JSON.parse(this.responseText);
        Ti.API.info(this.responseText);
        return obj;
    };

}

The problem is on the callback function. Because the method getDocument call correctly the web service and have a correct obj, but the callback function is not called.

bircastri
  • 2,169
  • 13
  • 50
  • 119

2 Answers2

2

You need a third argument to your getDocument function (it will be the callback function of your xhr request)

function getDocument(fiscalCode, date, success){
 var obj;
 var xhr = Titanium.Network.createHTTPClient();
 xhr.setTimeout(10000);
 xhr.open('POST', "http://url");

 xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 var myObject = {
     cf :fiscalCode,
     date_last_synchronization :date 
 };
 xhr.send(JSON.stringify(myObject));

  xhr.onerror = function() {
    Ti.API.info("SERVIZIO IN ERRORE");
    Ti.API.info(this.responseText);
    disattivaSemaforo();
 };


 xhr.onload = xhr.onload = function() {
    var obj = JSON.parse(this.responseText);
    Ti.API.info(this.responseText);
    success(obj);
 };

}

Then you can call getDocument function as you did before

getDocument("CFDECTEST02",null, function(obj) {
  Titanium.API.info("CALL BACK CHIAMATA "+ obj);
});
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
  • In addition it's always good practice to check that your callback is indeed a function like so: `if (success && typeof success === 'function') { success(obj) }` – James Aug 01 '16 at 08:08
1

You treat it like any other function and any other argument.

You are passing it as the third argument to getDocument, but you haven't give it a name in that function:

function getDocument(fiscalCode, date){

should be:

function getDocument(fiscalCode, date, callback) {

Then you just need to call it:

var obj = JSON.parse(this.responseText);
callback(obj);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335