Wordpress- How to use AJAX in WordPress

Below are easy steps to use AJAX in WordPress

STEP 1. Put the below code in your template file.

HTML

1
<a href="javascript:void(0)" id="click_to_ajax">Click Here to Ajax Request/response </a>

Script

1
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";

Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
jQuery(document).ready(function($) {  
 jQuery('#click_to_ajax').click(function() {
     
  var par1 = 'Banana';
  var par2 = 'Mango';
     
    jQuery.ajax({
   url: ajaxurl,
   data: {
    'action':'my_action_name',
    'par_1' : par1,
    'par_2' : par2,
   },
   success:function(data) {
     //console.log(data);
     alert(data);
   },
   error: function(errorThrown){
    //console.log(errorThrown);
     alert('Something is wrong');
   }
  });      
 });   
});

STEP 2. Put the bellow code in functions.php in your theme file.

1
2
3
4
5
6
7
8
function my_ajax_callback_function()
{
 
    print_r($_REQUEST);
}
    
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end

STEP 3. Make sure jquery libarary has been included for the page.

No comments:

Post a Comment