0
votes

I've integrated a bootstrap modal and included a .js file. The content of the js file is as below. The .js file is used to call Ajax. When I press the load more button, it fires the ajax function one time, which is good. But, once I closed the modal and open it again, and click on the load more button, it fires the ajax function twice. If I close the modal and open it again and click on the load more button, the ajax function fires thrice. My question is: How can I load the ajax function only one time if the load more button clicked? The scenario should be:

  1. I clicked on the load more and ajax called.

  2. I closed the modal and again open it. I clicked on the load more button and ajax fire (once only). If I clicked on the load more button again, it will call the ajax function once again.

and so on.

$(document).ready(function(){
   $(document).on('click','#btn-more',function(){
       var id = $(this).data('id');
       var token_csrf = $("#csrfToken").val();
       var base_path_loadata = $("input[name='base_path_loadata']").val(); 
       $("#btn-more").html("Loading....");
       $.ajax({
           url : base_path_loadata,
           method : "POST",
           data : {id:id, _token:token_csrf},
           dataType : "text",
           success : function (data)
           {
              if(data != '') 
              {
                  $('#remove-row').remove();
                  $('#load-data').append(data);
              }
              else
              {
                  $('#btn-more').html("No Data");
              }
           }
       });
   });  
});
<div id="remove-row">
                <button id="btn-more" data-id="{{$lastId}}" class="nounderline btn-block mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" ><span class="Cicon" ><i class="fa fa-paper-plane"></i></span> Load More </button>
            </div>
1
What happens if you change your listener to $('#btn-more').on('click',function() - Gezzasa
@Gezzasa the same happens! - Niladri Banerjee - Uttarpara

1 Answers

2
votes

Currently you add an event handler each time you open the modal (and load the script). Use off('click') to remove the previous event handler:

$(document).off('click','#btn-more').on('click','#btn-more', function...)