0

I have a jquery onClick function:

    $('body').on('click', '#id_name', function() {
...

and i would like to execute this function as another function on ajax call (currently this is only onclick).

if my ajax call is success then:

success: function() {
          // then execute top function 
        }

is it possible to do that?

2
  • you want callback function ? Commented Nov 21, 2016 at 16:48
  • So make it a function and call the function. Commented Nov 21, 2016 at 16:51

4 Answers 4

5

Then you can use $('#id_name').trigger('click') in the ajax success callback.

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

Comments

2

Make the function a named (non-anonymous) function:

var someFunction = function () {
    //...
};

Then you can use it for your click event:

$('body').on('click', '#id_name', someFunction);

Or your callback:

success: someFunction

Or invoke it from therein:

success: function () {
    someFunction();
}

etc. Basically once you give the function a name and it's no longer anonymous you can refer to it anywhere that it's in scope.

Comments

1

Create a delegate function and call it separately

for example

function mainFunction(){
// Rest of code
} 

on click call this

$('body').on('click', '#id_name', mainFunction)

Inside ajax success call like this

success: function() {
          mainFunction()
        }

Comments

1

Well, you could explicitly trigger the click event. Or even better, outsource your click code in an own function and then you can call it inside your success function. So, instead of

success: function() {
    $('#id_name').trigger('click')
}

Do better this:

function clickEvent() {
    // do something in here...
}
$('body').on(
    'click',
    '#id_name',
    function (eventArgs) {
        eventArgs.preventDefault();
        clickEvent();
    }
);

And then you can simply call it into your success callback with:

success: function() {
    clickEvent();
}

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.