If I have object myApi with execute function
var api = new myApi();
api.execute();
Inside execute I have (*that is myApi instance)
function execute() {
$.ajax({
type: this.getRequestMethod(),
data: this.getDataParams(),
complete: function(xmlHttp){
that.setResult(jQuery.parseJSON(xmlHttp.responseText));
that.setHttpStatus(xmlHttp.status);
},
url: this.getUrl(),
beforeSend: setHeader
});
}
How can I make callback/listener so I can do this
var api = new myApi();
api.execute();
var result = api.getResult();
var statusCode = api.getStatusCode();
switch(statusCode) {...};
if I leave it just this way, these bottom two lines are executed before ajax call is finished (complete isn’t called yet) so I have undefined variables.
You can’t do it that way, unless you would force the AJAX requests to be syncronous (which probably is a bad idea). You need need to attach somekind of callback method, you can also use some jQuery
Deferredmagic.Therefore, return the
jqXHRobject which encapsulates aDeferred:and then use it like