User1v0
User1v0

Reputation: 63

Invoke Ajax function from Bootstrap modal button

I'm looking to invoke an ajax function after clicking an option from a bootstrap confirmation modal. the confirmation modal will be open through function remove(parameter)

Any help will be appreciated

function remove(parameter){
	// $("#remove-modal").modal('show');
	/*
  if( modal clicked Yes){
  ..perform ajax call using 'parameter'
  }
	*/
}
<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="remove-modal">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Do you want to remove this item?</h4>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" id="modal-btn-si">Yes</button>
        <button type="button" class="btn btn-primary" id="modal-btn-no" data-dismiss="modal">No</button>
      </div>
    </div>
  </div>
</div>

Upvotes: 0

Views: 729

Answers (2)

Tieson T.
Tieson T.

Reputation: 21237

I would assume adding a click handler to the "Yes" button, after the modal is shown, should work. Something like:

function remove(parameter){
    // show the dialog
    var m = $("#remove-modal").modal('show');

    // find the button in your modal, and attach an event 
    // handler to it's click event
    m.on('shown.bs.modal', function(){
        m.find('#modal-btn-si').on('click', function(e){

            // do something here...

            // When you're ready to dismiss the modal, call:
            //
            // m.modal('hide');
            //
            // Make sure this is in the callback for your
            // AJAX event, unless you want the modal dismissed
            // as soon as the button is clicked
        });
    });
}

Upvotes: 0

NielsNet
NielsNet

Reputation: 828

You could just add an event listener for the yes button. As the event varies every time the modal is shown you remove it before adding the new one.

remove(parameter) {
    var yesButton = $("#modal-button-si");
    yesButton.off("click");
    yesButton.click(function(){
        //perform ajax here
    });
} 

Upvotes: 1

Related Questions