JorgeeFG
JorgeeFG

Reputation: 5941

Javascript Scope (Jquery)

I have an Ajax Call, in an OnClick event.

Inside the OnClick, I set a var type = $(this).closest("table").attr("id");

I am trying to call this type inside the Ajax's complete function().

But it shows as undefined.

Maybe someone can explain a lil bit why this is happening?

Thanks!!

$(document).on('click','.swaction',function(event){
    var pdfId = $(this).closest('tr').find('td:first').html();
    var type = $(this).closest("table").attr("id");
    event.preventDefault();

    if( $(this).data('action') === 'delete' )
    {
      var currentElement = this;
      if( confirm( "¿Está seguro de querer eliminar el \nPDF Nº " + pdfId + '?' ) )
      {
        $.ajax({
          url: 'ct_form_procesar_escaneos/pdf/delete/'+ type + '/' + pdfId,
          method: 'POST',
          error: function( jqXHR, textStatus, errorThrown )
          {
            alert( errorThrown );
          },
          complete: function()
          {
            var a = type; // undefined
            $(currentElement).closest('tr').fadeOut(600, function(){
              $(currentElement).remove();
              $.procesar_escaneos.removeOnEmpty( type );
            });
          }
        });
      }
    }

Upvotes: 1

Views: 84

Answers (1)

mor
mor

Reputation: 2313

In javascript, the this keyword takes it's context dynamically depending of the function it is called from. When you call type from within an Ajax callback, the context has changed and this is not the same object.

Since javascript uses lexical scoping, you can save a reference to the this object when the context is right and then use this reference in your function.

var self = this;
var type = $(self).closest("table").attr("id");

This will work.

Upvotes: 2

Related Questions