Tengo una función en JS y jQuery que activa una llamada AJAX y tiene un bloque de callback de llamada para avisarme cuando haya terminado:
function ajaxCall(url, type, dataType, dataToSend, callback) { if (dataType == undefined) dataType = "json"; if (dataToSend == undefined) dataToSend = null; $.ajax({ url: url, type: type, dataType: dataType, contentType: "application/json", data: dataToSend, async: true, success: function (result) { callback(result); }, error: function (data, status) { console.error("Server Error: " + status); } }); } ¡Estoy accediendo así, pero usar funciones externas como showAjaxLoader() simplemente no funciona! dice que esta función no está definida:
function registerUser(data) { ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) { // SOME CODE THAT RUNS WHEN IT'S COMPLETE // External method: showAjaxLoader(false); // Doesn't work }); }); function showAjaxLoader(show) { var loader = $('.ajax-loader'); if (show) { loader.fadeIn("fast"); } else { loader.fadeOut("fast"); } }¿Qué estoy haciendo mal?
Gracias :)
¿Has intentado hacer algo como:
var that = this; function registerUser(data) { ajaxCall(pathServiceRegister, "POST", undefined, JSON.stringify(data), function (result) { // SOME CODE THAT RUNS WHEN IT'S COMPLETE // External method: that.showAjaxLoader(false); }); });Resolvió alguna muestra. esto puede ser una buena práctica. Prueba esto :
$(document).ready(function() { $("button").click(function() {registerUser();}); }); var Scallback = function(arg) { alert("Success :"+arg); showAjaxLoader(true); } var Ecallback = function(arg) { alert("Err :"+arg); showAjaxLoader(true); } function showAjaxLoader(show) { var loader = $('.ajax-loader'); if (show) { loader.fadeIn("fast"); } else { loader.fadeOut("fast"); } } function ajaxCall(url, type, Scallback, Ecallback) { $.ajax({ url : url, type : type, async : true, success : function(result) { Scallback(result); }, error : function(data) { Ecallback(data) } }); } function registerUser() { ajaxCall(pathServiceRegister, "GET", Scallback, Ecallback); }Declara tu método así
var obj = { showAjaxLoader : function(show) { var loader = $('.ajax-loader'); if (show) { loader.fadeIn("fast"); } else { loader.fadeOut("fast"); } } }Luego, dentro de ajax, llama a obj.showAjaxLoader(false); Esto puede funcionar.