4
Can anyone tell me how to create functions with callback? I created this function but it’s not working.
function PostsCategoriasListar(table, select, callback) {
if (table) {
$.ajax({
url: controller_dashboard,
type: 'POST',
dataType: 'json',
data: {acao: 'PostsCategoriasListar', Listar: 'table'},
success: function(response) {
if (response.status === 'LogOff') {
window.setTimeout(function() {
window.location.reload();
}, 10000);
}
$element.find('table tbody').html(response.table);
ExecuteDataTable(0, maximo, 1);
},
error: function(error) {
console.log(error);
}
});
}
if (select) {
$.ajax({
url: controller_dashboard,
type: 'POST',
dataType: 'json',
data: {acao: 'PostsCategoriasListar', Listar: 'select'},
success: function(response) {
if (response.status === 'LogOff') {
window.setTimeout(function() {
window.location.reload();
}, 10000);
}
$element.find('form select').html(response.select);
},
error: function(error) {
console.log(error);
}
});
}
//EU QUERO QUE O CALLBACK SO EXECULTE DEPOIS QUE TODO CODIGO QUE ESTIVER NOS IF'S ACIMA TENHAN TERMINADO, ELE SEMPRE EXECULTA ANTES ONDE ESTOU ERRANDO?
if (typeof callback === 'function')
callback();
}
PS: I did not put the ajax requests because it would make it too big and they are working only I need them to execute first and after they finish the callback is executed
Place the call to
callback()within itselfsuccess. Since Ajax calls are asynchronous (by default), if you put it off it will be called before Ajax even starts. There is no problem in referring to a function variable within another more internal function (i.e. closure).– mgibsonbr