1

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 );
            });
          }
        });
      }
    }
7
  • 1
    Did you check if the type is defined after your initialization? Commented Jun 13, 2013 at 21:08
  • Yes, because the URL works good having type Commented Jun 13, 2013 at 21:09
  • Scope seems ok. have you tried using a different variable name? maybe this one is overwritten somehow on a different scope. Commented Jun 13, 2013 at 21:24
  • Yep, you're gonna have trouble doing this. Especially with jQuery you run into weird hoisting issues. Check out this article and see if it helps you. Commented Jun 13, 2013 at 21:25
  • 1
    I made a simple test based on your code with jsfiddle, and it appears to work fine: jsfiddle.net/aHA5a/1, at least on my browser. Can you check on your side ? Commented Jun 13, 2013 at 21:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.