0

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>');
            }
        }
    });
});
potashin
  • 44,205
  • 11
  • 83
  • 107
  • Again and again. `this` is not this before you run something asynchronous . Set `this` to `somehingElse` before you run `$.ajax`. – Alex Kudryashev May 29 '16 at 01:30

1 Answers1

0

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).

potashin
  • 44,205
  • 11
  • 83
  • 107