0

I'm using jQuery bootstrap modal. I would like the caller of the modal to pass a function to it somehow so that when the modal has successfully done it's thing, it can execute the function that the caller passed to it. If the modal is cancelled/dismissed, this function should not be executed.

How can this be done?

My caller code is something like this

var doSomething = function() {
   // some code here
}

$('#aBtn').click(function() {
   #('#myModal').modal();
   // if the modal is dimiseed using cancel button do no nothing.
   // The modal submits an ajax form, if it is successful then execute the following function
   doSomething();
});
user205892
  • 311
  • 1
  • 8
  • 1
    It seems that you'd execute `doSomething()` depending on the result of the AJAX submission. – showdev Sep 04 '21 at 16:20
  • call doSomething() method after ajax successfully submitted. – glovemobile Sep 04 '21 at 16:39
  • I forgot to mention that doSomething is in a separate ASP.NET mvc control and the modal is in a separate control. Can I somehow pass the doSomething function to ('#myModal').modal() ? – user205892 Sep 05 '21 at 01:02

2 Answers2

0

I am using this link as the basis for my answer : jQuery's .click - pass parameters to user function

What you could try is :


var doSomething = function() {
   // some code here
}


$("#aBtn").click({ myFunc: doSomething }, function() { 
   // do you logic here
   event.data.myFunc();
})
tsamridh86
  • 1,480
  • 11
  • 23
0

Its not necessary to code the case of dismissing a modal. This click function will only work if the btn with id #aBtn is clicked, making it impossible to do both things of closing the modal and clicking the btn.

If you are not familiar with ajax as you can see there are two functions you can implement once the ajax executes. The success:function() and the error:function(). If everything goes well ajax allows you to do things after that. Instead of creating another function you can make the success:function() your doSomthing method.

var doSomething = function() {
   // Add this code in the success:function() method inside ajax
}

$('#aBtn').click(function() {
   
   #('#myModal').modal();

   // The modal submits an ajax form
   $.ajax({
        method: '',
        url: "",
        data: { },

        // If ajax is successful execute the following function                       
        success:function(){ // Do something },

        // If ajax has an error then it will log the following msg
        error:function(){  console.log('AJAX error')  }
    });
});
Gass
  • 7,536
  • 3
  • 37
  • 41