Wordpress plugin jQuery script call to admin-ajax.php works only once

231 views Asked by At

I'm writing a little wordpress plugin. The plugin has a simple script that interacts with a datatable in the backend.

It is used to duplicate a row in the table by clicking a button, and then insert the data in the database. I'm using a setTimeout(function () {} because the table loads through ajax, and i need to wait that the button is in the DOM.

It works, but only on the first click, nothing happens if i click the button a secon time, i have to referesh the page to make it working again.

here is my code:

setTimeout(function () {
  var duplicate = $('#wpbody-content').find("[data-action=duplicate]");
  duplicate.each(function() {
    $(this).on('click', function() {
      //console.log('click');
      var rate = $(this).parent().parent().next().find('.custom-control-input').val();
      //console.log(value);
      $.ajax({
        url: '/wp-admin/admin-ajax.php',
        data: {
          action: 'duplicate_row',
          'duplicate_ajax': rate
        }, success: function(data){
          //console.log('SUCCESS');
          $('#my-table').DataTable().ajax.reload(null, false);

        }
      });
    });
  });
}, 3000);
1

There are 1 answers

5
Moishy On BEST ANSWER

I would wrap it in a function so like this it can be called on demand.

it would be better to add a class to each element duplicate and then call it like that.

Also to not it is better to define you ajax url on the page via PHP so there is a consistency when you call wordpress ajax.

wp_localize_script( 'YOUR_ENQUEUED_SCRIPT', 'site', array('ajaxurl' => admin_url( 'admin-ajax.php' )) );

Then in your js:

function addRow(rate){
    $.ajax({
        url: site.ajaxurl,
        data: {
          action: 'duplicate_row',
          'duplicate_ajax': rate
        }, success: function(data){
            //console.log('SUCCESS');
            $('#my-table').DataTable().ajax.reload(null, false);
        }
    });
}


$('#wpbody-content').on("click", ".duplicate", function(e){
    e.preventDefault();
    let rate = $(this).parent().parent().next().find('.custom-control-input').val();
    addRow(rate);
});