PacPac PacPac - 6 months ago 9
jQuery Question

In jQuery $(this) don't return me the current element

I'm trying to show a particular text an icon depending cases.

For example, if datas are successfully saved I show a 'Your datas are saved.' and the right icon.

My problem is before the

$.ajax
part, all is working but after, I think my
$(this).find(...)
don't return me the element.

Is it possible ?

Here's my code:

$('form.modal-form').on("submit", function (event) {
event.preventDefault();

icon = 'fa-spinner fa-pulse';
text = 'Save in progress';
$(this).find('.modal-footer .pull-left').html('<i class="fa ' + icon + ' fa-fw"></i><span class="hidden-xs">' + text + '</span>');



$.ajax({
type : 'POST',
data : $(this).serialize(),
url : 'assets/php/ajax/'+$(this).data('target')+'.php',
success: function(response){
var json = $.parseJSON(response);
if(json.type=='success'){
icon = 'fa-check';
text = json.message;
$(this).find('.modal-footer .pull-left').html('<i class="fa ' + icon + ' fa-fw"></i><span class="hidden-xs">' + text + '</span>');
}
if(json.type=='error'){
icon = 'fa-exclamation';
text = json.message;
$(this).find('.modal-footer .pull-left').html('<i class="fa ' + icon + ' fa-fw"></i><span class="hidden-xs">' + text + '</span>');
}
}
});
});

Answer

In the ajax callback this refers to a different object from the one in the submit handler, so not to lose it, you should assign it to something in the first place (to make it visible in the callback afterwards), after event.preventDefault, for example:

var that = $(this)

And use that instead of $(this).

Comments