Custom ajax requests in wordpress Custom ajax requests in wordpress wordpress wordpress

Custom ajax requests in wordpress


There are WordPress ajax hooks that helps to create function using ajax. Wordpress allows admin ajax to run any function. Following code is help to use custom ajax in wordpress.

<?php// javascript ajax call with click eventadd_action('wp_head', 'ajx_action_javascript_wp');function ajx_action_javascript_wp() {?><script type="text/javascript" >jQuery(document).ready(function($) {    $('.myajax').click(function(){      //alert(1);      var mydata = $(this).data();      //var termID= $('#locinfo').val();      $('#wpajaxdisplay').html('<div style="text-align:center;"><img src="<?php echo get_template_directory_uri(); ?>/images/bx_loader.gif" /></div>');      //console.log(mydata);        var data = {            action: 'custom_action',            //whatever: 1234,            id: mydata.id        };        $.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {           // alert('Got this from the server: ' + response);           $('#wpajaxdisplay').html(response);              });    });});</script><?php}add_action('wp_ajax_custom_action', 'custom_action_callback_wp');add_action( 'wp_ajax_nopriv_custom_action', 'custom_action_callback_wp' );function custom_action_callback_wp() {     global $wpdb; // this is how you get access to the database     $getid = 'ID=> '. $_POST['id'];     echo $getid;     // do something     exit(); // this is required to return a proper result} ?>

HTML Part

<a href="#ajaxthing" class="myajax" data-id="600">Click On this</a><div id="wpajaxdisplay">Ajax Result will display here</div>


I think one easy method is to create a new template and assign this template to a new page.then you can write your code in this template file and use the url of the page for ajax request