There is a page where data is inserted using an ajax request. Here is a piece of code:

 foreach ($sql_object as $ps){ $i++; ?> <div id="<?= $i?>" class="getApiId">...</div>} 

First I print the list in a loop. After that, by clicking on the block, I take from the data-api block

 $('.getApiId').on('click', function() { //Показать поставщика var url = '...'; var api_id = $(this).attr('data-api'); var data = {...}; async_query(url,data); }); function async_query(url,data) { $.ajax({ url:url, type:'POST', data:data, dataType: 'html', success: function(html){ if(this_show != 0) { $('...').html(html).show(); } } }); } 

The problem is that the code loops, i.e. when I select an item from the list for the first time, then all the rules, and when the second, third time ... I get a bunch of button presses that double each time. Tell me, please, what's the problem?

    1 answer 1

    Code

     $('.getApiId').on('click', ... 

    performed multiple times.

    Replace it with

     $(document).on("click", ".getApiId", function () { ... 

    and call only once in $(document).ready(function(){ ... }); .

    • It did not work. PS event handler is already in $(function(){... - r.mcreal
    • @ r.mcreal What is in the html variable that is served in success ? - Igor