0

I am confused why this code is not working:

HTML:

<li><a id="faktura-generate" rel="regular">Faktúra</a></li>
<li><a id="proforma-generate" rel="proforma">Zálohová faktúra</a></li>

JS:

$('#faktura-generate, #proforma-generate').live('click', function () {
    var type = $(this).attr('rel');
    $.ajax({
        url: 'index.php?route=sale/order/superfaktura&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>&type=' + type,
        dataType: 'json',
        beforeSend: function () {
            $(this).after('<img src="view/image/loading.gif" class="loading" style="padding-left: 5px;" />');
        }
    });
}); 

I want to show a little loading icon after user clicks one of the link. $("#proforma-faktura").after(...) is working, but $(this).after(...) not.

AntouanK
  • 4,880
  • 1
  • 21
  • 26
Adrian
  • 2,576
  • 9
  • 49
  • 97
  • You forgot a dollarsign ? – adeneo Jun 26 '13 at 18:41
  • And live() is deprecated and removed in newer versions of jQuery. – adeneo Jun 26 '13 at 18:41
  • And `this` is probably `$.ajax`, not the clicked element, as it's in another function scope. – adeneo Jun 26 '13 at 18:42
  • Use `context: this` in the AJAX options – Ian Jun 26 '13 at 18:42
  • @Ian - sounds like an answer! Wasn't aware that `context` worked in the `beforeSend` handler as well, I was sure it only worked in `success` and `error`, as I struggled with that some time ago, but testing it, it does seem to work fine. – adeneo Jun 26 '13 at 18:47
  • @adeneo From the docs: `This object will be made the context of all Ajax-related callbacks.`, so I'd assume `beforeSend` is included in that list :) I'd create an answer, but this is already a duplicate, so I don't want to encourage like the current answer – Ian Jun 26 '13 at 18:48

1 Answers1

3

this is not referring to your element in the anonymous function you pass to the 'beforeSend'.

you can try to capture it in a closure

$('#faktura-generate, #proforma-generate').live('click', function () {
    var that = this,  //  capture 'this' here
        type = $(this).attr('rel');

    // make a function with access to 'that'
    var myFun = function (data) {
        $(that).after('<img src="view/image/loading.gif" class="loading" style="padding-left: 5px;" />');
    };

    $.ajax({
        url: 'index.php?route=sale/order/superfaktura&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>&type=' + type,
        dataType: 'json',
        beforeSend: myFun
    });
});

try it.

also live is not supported anymore, try another way. ( version deprecated: 1.7, removed: 1.9 )

AntouanK
  • 4,880
  • 1
  • 21
  • 26
  • Thank you, it's working now. OpenCart still uses jQuery 1.7, but good to know, that the .live() was removed. Edit: I not created another myFun function, but simply var that = this ,,, $(that).after() is working. :) – Adrian Jun 26 '13 at 18:57