Riccardo Riccardo - 1 month ago 13
Ajax Question

Javascript call to function not available

i have a problem with a script javascript. I have an object with inside some function and variable. In one of these function i make an ajax request and inside the error handler i call a function defined in the same object but the debugger say that the function is "not available" but the variables defined in the object are visible...

This is the portion of Javascript with the object:

Utils = {
"defaultErrorMessage" : "Ci scusiamo per il disagio ma qualcosa è andato storto, probabilmente è una cosa temporanea, ritenta in un altro momento",
"base_url" : $('#base_url').val(),
getApiUri : function(name) {
return window.location.protocol + "//" + window.location.host + PATH[ENV] + name + ENV == 'stub' ? '.json' : '';
},

callServer : function(uri, data, successCallback) {
$.ajax({
type: "POST",
url: this.base_url + "index.php/" + uri,
data: data,
dataType: "json",
cache: false,
beforeSend: function(XMLHttpRequest)
{
waitingDialog.show('Caricamento...');
},
success:
function (data) {

//alert(data); //as a debugging message.
successCallback(data);
},
error: function (xhr, ajaxOptions, thrownError) {
//alert("Qualcosa di storto: "+ xhr.status + " messaggio: " + xhr.responseText);
this.showModalDialog('error','Siamo spiacenti :(', this.defaultErrorMessage);
},
complete: function() {
waitingDialog.hide();
}
});
},

hideAllMessages: function ()
{
var messagesHeights = new Array(); // this array will store height for each

for (i=0; i<myMessages.length; i++)
{
messagesHeights[i] = $('.' + myMessages[i]).outerHeight();
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
},

showMessage: function(type, title, message) {
var title = (typeof title !== 'undefined') ? title : '';
var message = (typeof message !== 'undefined') ? message : '';

this.hideAllMessages();
if (title != '')
$('.'+type + ' h3').html(title);
if (message != '')
$('.'+type + ' p').html(message);
$('.'+type).animate({top:"0"}, 500);
},

showModalDialog: function(type, title, message, withOK) {
var withOK = (typeof withOK !== 'undefined') ? withOK : false;
$div = $('<div id="error" title="'+title+'">');
$div.append('<p>'+message+'</p>');
if (!withOK) {
$div.dialog({
modal: true,
maxHeight: 500
}).prev(".ui-dialog-titlebar").css("background", colorDialog[type]);
}
else {
$div.dialog({
modal: true,
maxHeight: 500,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
}).prev(".ui-dialog-titlebar").css("background", colorDialog[type]);
}
},

validateEmail: function(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}


};

Why this.showModalDialog is not available in the error handler? I have tried also without "this" but is the same...

Answer

this doesn't always work in callback functions because the context changes so this is referring to something that is no longer your Utils object. The way to fix this is by keeping a variable to remember what your context is when you need it. In your callServer function, before the ajax call, add var self = this. And then when you need to reference showModalDialog, you can call it with self.showModalDialog();

callServer : function(uri, data, successCallback) {
     var self = this;
     $.ajax({
       ...
          self.showModalDialog();