Below are easy steps to use AJAX in WordPress
STEP 1. Put the below code in your template file.
HTML
Click Here to Ajax Request/response
Script
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
Script
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.
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