I am trying to modularize my JS code by creating an API module, where I can retrieve all required data using Liferay's AUI ajax features. Currently I have this:
var API = (function() {
var getAsistencias = function(idEdicion, periodo) {
AUI().use('aui-io-request', function(A) {
A.io.request('myapiaddress', {
method : 'post',
dataType : 'json',
data : {
_mypackage_WAR_myportlet_periodo : periodo,
idEdicion : idEdicion
},
on : {
success : function() {
data = this.get('responseData');
return data;
}
}
});
});
};
return {
getAsistencias : getAsistencias,
}
})();
However when I call it like this:
var data = API.getAsistencias(id, dataInfo);
Data is always null even though in the onSuccess method it is actually retrieving the data correctly. What am I doing wrong?
Also how can I manage errors?
The main problem here is you are not returning anything from your functions. This should be something like this
var API = (function() {
var getAsistencias = function(idEdicion, periodo,callback) {
AUI().use('aui-io-request', function(A) {
A.io.request('myapiaddress', {
method : 'post',
dataType : 'json',
data : {
_mypackage_WAR_myportlet_periodo : periodo,
idEdicion : idEdicion
},
on : {
success : function() {
data = this.get('responseData');
callback(data);
}
}
});
});
};
return {
getAsistencias:getAsistencias
};
})();
API.getAsistencias(id,periodo,function(data){
Console.log(data);
//Do something here
});