Jacob Raccuia
Jacob Raccuia

Reputation: 1686

jQuery function called before and after ajax behaving weirdly

I am trying to call one function before and after an ajax request. First, I pass "loading" and it displays the loading gif. On ajax success, it passes a success message and displays that instead.

Here is my js/jquery

$.fn.loading_success = function(action) {
            // action var is either "loading" or a success message
        this.siblings('div.loading').remove();
        this.siblings('div.success').remove();

        console.log(action);

        if(action == 'loading') {
            this.after('div class="loading"> /div>'); // note this would actually be kosher html
        } else { 
            this.after('div class="success">' + action + '/div>'); // like above, kosher html
        }

        return this;

    }

    $('.action').on('click', function(e) {
        e.preventDefault();
        $(this).loading_success('loading');

    var dataPass = 'goodbye='+ 'world';
    $.ajax({
        type: "POST",
        url: "/echo/json/",
        data: dataPass,
        cache: false,
        success: function(){        
            var success_message = "We've got a winner!";
            $(this).loading_success(success_message);
        }
    });
    });

and the JSfiddle is here.

My actual AJAX response looks a bit different, but I rewrote it so it works in jsfiddle.

The weirdest thing is that the console log displays the two different responses I'd expect. I feel like this is a silly jquery error the more I think about it , but I'm stumped.

Upvotes: 1

Views: 116

Answers (1)

A. Wolff
A. Wolff

Reputation: 74410

Use ajax option context:

DEMO jsFiddle

$.ajax({
        context: this, //<< HERE!
        type: "POST",
        url: "/echo/json/",
        data: dataPass,
        cache: false,
        success: function(){        
            var success_message = "We've got a winner!";
            // then in success callback, 'this' refers to clicked element
            $(this).loading_success(success_message);
        }
    });

Upvotes: 2

Related Questions