wordpress user
wordpress user

Reputation: 584

hook into ajax success later

I am writing a plugin , there is an ajax call which displays the data to user.
If user wants to add some js on ajax success? can he do it from his js script , like target this ajax success event.
For example:

 $(document).on('click','button',function(){
    $.ajax({
        url: 'url.php',
        success: function(response){
            /** HOOK HERE **/
            $('.display').html(response);
        }
    })
})

Now user wants to add this alert('User data'); to ajax success call

Upvotes: 1

Views: 853

Answers (1)

slebetman
slebetman

Reputation: 114094

You just need to remember that functions are objects just like numbers, strings etc. So you can provide a variable for him to attach a function to and call that if available:

MyPlugin = {
    onAjaxSuccess: null
};

$(document).on('click','button',function(){
    $.ajax({
        url: 'url.php',
        success: function(response){
            /** HOOK HERE **/
            if (typeof MyPlugin.onAjaxSuccess == 'function') {
                MyPlugin.onAjaxSuccess(response);
            }
            $('.display').html(response);
        }
    })
})

So now your users can do:

MyPlugin.onAjaxSuccess = function (response) {
    console.log(response)
};

Wait, where have I seen this before?

This is a similar API to the old-school DOM .onXXX callbacks. Just like

document.getElementById('myButton').onclick = function () {
    alert('HA');
};

Looks too old-school.

If you want your API to look a bit more modern and all fancy you can emulate jQuery's style:

MyPlugin = {
    onAjaxSuccess: null,
    on: function (e_type,callback) {
        if (e_type == 'ajaxSuccess') {
            this.onAjaxSuccess = callback;
        }
    }
};

Now your users can do this:

MyPlugin.on('ajaxSuccess',function(result){
    console.log(result);
});

Upvotes: 1

Related Questions