Thursday, May 21, 2015

Wordpress- How to use AJAX in WordPress

Wordpress- How to use AJAX in WordPress

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

<a href="javascript:void(0)" id="click_to_ajax">Click Here to Ajax Request/response </a>
           
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

<script type="text/javascript">
    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');
            }
        });     
       
    });
           
    });
</script>

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

<?php
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. Be sure jquery libarary is included for the page. 


Njoy Your DaY :)

1 comment :

  1. Voila!!! amazing tutorial...it almost saved my day....

    ReplyDelete