Tuesday, May 7, 2019

How to make a ajax call in my custom wordpress plugin.

Step1: Now you have to add the below function in the functions.php file in your plugin

/* If you wanted to also use the function for non-logged in users*/
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' ); 
/* with logged in users*/
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() { global $wpdb; // this is how you get access to the database $id = intval( $_POST['id'] ); $status = $_POST['status']; echo 'whatever'; die(); // this is required to terminate immediately and return a proper response }
Step2: Client Action
    <a href="javascript:void(0)" class=" btn btn-block btn-success actionActive" >Yes Action</a>
 <script>
 $(document).on('click','.actionActive',function(){
 
 var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
      var data = {
        'action': 'my_action',
        'id'    : '1',
        'status': '2'
      };
      // We can also pass the url value separately from ajaxurl for front end AJAX implementations
      jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
      });
   
  });
  </script>