Sunday, May 31, 2015

How to implement ajax in wordpress?

index.php

1)
<a onclick="fnRequest()">Test Request</a>
<a id="response_text"></a>


2)
<script type="text/javascript">
function fnRequest()
{
    var data = {};
    data.register_email = "test";
    data.action = "request_action";
    jQuery.post('<?php echo rawurldecode(esc_url(home_url( '/'))); ?>wp-admin/admin-ajax.php',data, responsefunction);
}
function responsefunction(result)
{
    $("#response_text").html(result);
    //alert(result);
}
</script>


3)
functions.php

add_action('wp_ajax_request_action', 'request_action');
add_action('wp_ajax_nopriv_request_action' , 'request_action');
function request_action()
{
    echo "Testing response";
}

No comments:

Post a Comment

Please mention your comments.......