How to prevent recalling the same jQuery function from AJAX response and make the jQuery functionality workable?

StackOverflow https://stackoverflow.com/questions/23546468

Question

I've an HTML form. When the page loads it contains only one <div> I'm calling AJAX function to append <div>. But the javascript which works on HTML content when page loads doesn't work on the content I appended through AJAX. So in order to make the jQuery functionality workable on the content appended through AJAX response. I rewrote the same function in AJAX response. Now the issue arises. The function I wrote in $(document).ready(function{...}) as well as the same function which I wrote in AJAX response gets called. That is the function gets called repeatedly. The function in AJAX gets called exactly the equal no. of <div> I appended. How to avoid this and make the jQuery functionality workable on all the elements including the elements added using AJAX? For your reference I'm giving below my code:

//Below is the function code which I written when document is ready
$(document).ready(function() {
  $('.products').click(function () {
    var table_id = $(this).closest('table').attr('id');

    var no = table_id.match(/\d+/)[0];            
    //var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
    var first_row = $('#'+table_id).find('tbody tr:first').attr('id');

    var new_row = $('#'+first_row).clone();
    //var tbody = $('tbody', '#'+table_id);
    var tbody = $('#' + table_id + ' tbody');
    var n = $('tr', tbody).length  + 1;
    new_row.attr('id', 'reb' + no +'_'+ n);

    $(':input', new_row).not('.prod_list').remove();
    $('select', new_row).attr('name','product_id_'+no+'['+n+']');
    $('select', new_row).attr('id','product_id_'+no+'_'+n);
    $('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_row.find('td:first')) );
    tbody.append(new_row);
    $('.delete').on('click', deleteRow);
   });
});

//Below is the AJAX function code which I'm using to append content. It also contains the same above function code


  function add_rebate_by_product() {
  if($.active > 0) { //or $.active      
    request_inprogress();
  } else {
    var manufacturer_id =  $("#company_id").val();
    var rebate_no       =  $('.rbt').length;

    if ($('.rbt').length>=0) { 
      rebate_no = rebate_no+1;
    }
      $('.add_new_rebate').attr('disabled','disabled');
    }

    $.ajax({
      type: "POST",
      url: "add_rebate_by_product.php",
      data: {'request_type':'ajax', 'op':'create_rebate', 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},  
      beforeSend: function() { 
        $('.load_img').html("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
      },
      success: function(data) {
        if(jQuery.trim(data)=="session_time_out") {
        window.location.href = site_url+'admin/login.php?timeout=1';                
        } else {
          $('.rebate_block').append(data);
          $('.add_new_rebate').removeAttr('disabled');

          $('.states').multiselect({
            includeSelectAllOption: true,
            maxHeight: 150
          });
          $(".date_control").datepicker({
            dateFormat: "yy-mm-dd"
          });
          $('.products').click(function () {
            var table_id = $(this).closest('table').attr('id');

            var no = table_id.match(/\d+/)[0];            
            //var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
            var first_row = $('#'+table_id).find('tbody tr:first').attr('id');

            var new_row = $('#'+first_row).clone();
            //var tbody = $('tbody', '#'+table_id);
            var tbody = $('#' + table_id + ' tbody');
            var n = $('tr', tbody).length  + 1;
            new_row.attr('id', 'reb' + no +'_'+ n);

            $(':input', new_row).not('.prod_list').remove();
            $('select', new_row).attr('name','product_id_'+no+'['+n+']');
            $('select', new_row).attr('id','product_id_'+no+'_'+n);
            $('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_row.find('td:first')) );
            tbody.append(new_row);
            $('.delete').on('click', deleteRow);
            });         
        }
        $('.load').remove();
      }
    });
//}
}

I've written the same javascript function in AJAX response body as when AJAX gets called the javascript object gets destroyed and we need to again recreate the javaceript object in order to make the jQuery functionality workable. But the issue I'm facing is the function is getting called multiple times instead of once only when the request is made for it. Please help me in this regard. Thanks in advance. I you need any further information regarding the question I can provide you the same.

Was it helpful?

Solution

First thing I'd like to point out the wrong thing you are doing is you are writing the same jQuery function twice at different positions in your code. This is an unnecessary code redundancy. It's a very bad style of programming. If you write the function in following fashion you will get everything working fine. Also remove the same function code you have written in AJAX response.

$(function () {
  $(document).delegate('.products','click',function (e) {
    var table_id = $(this).closest('table').attr('id');

    var no = table_id.match(/\d+/)[0];            
    //var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
    var first_row = $('#'+table_id).find('tbody tr:first').attr('id');

    var new_row = $('#'+first_row).clone();
    //var tbody = $('tbody', '#'+table_id);
    var tbody = $('#' + table_id + ' tbody');
    var n = $('tr', tbody).length  + 1;
    new_row.attr('id', 'reb' + no +'_'+ n);

    $(':input', new_row).not('.prod_list').remove();
    $('select', new_row).attr('name','product_id_'+no+'['+n+']');
    $('select', new_row).attr('id','product_id_'+no+'_'+n);
    $('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">&times;</button>').appendTo( $(new_row.find('td:first')) );
    tbody.append(new_row);
    $('.delete').on('click', deleteRow);

  });  
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top