Pages

Feb 19, 2016

WordPress Sample Ajax Function For Any Theme Or Plugin

WordPress sample ajax function for any theme or plugin.
Place this in a template page or any custom page(.php)



<script>
jQuery(‘.click_button’).click(function(){
var id = jQuery(this).attr(‘id’);
var security = ‘<?php echo wp_create_nonce( ‘check-nonce’ ); ?>'; //You can name it anything you like //This is important
jQuery.ajax({
url:”<?php echo admin_url(‘admin-ajax.php’); ?>”,
type:’POST’,
// data:’action=del_image&img_id=’ + img_id,
data:’action=actionhere&id=’+id+’&security=’+security ,
success:function(results)
{
alert(results);//Or any required action
}
});
});
</script>
place this in theme’s/plugins’s function.php

<?php
add_action(‘wp_ajax_actionhere’, ‘actionhere_callback’);
add_action(‘wp_ajax_nopriv_actionhere’, ‘actionhere_callback’);
function actionhere_callback() {
$id = $_POST[‘id’];
$do_check =check_ajax_referer( $security,’check-nonce’,false );
//————————–custom function start————-//
/**************************************************************/
/****** ********/
/****** CUSTOM FUNCTION ********/
/****** ********/
/**************************************************************/
//————————–custom function end————-//
die();//This is important
}
?>

No comments: