Skip to content

Instantly share code, notes, and snippets.

@flowdee
Created March 2, 2019 08:26
Show Gist options
  • Save flowdee/5ba9ec83a271f26ac6705e8a0d160fae to your computer and use it in GitHub Desktop.
Save flowdee/5ba9ec83a271f26ac6705e8a0d160fae to your computer and use it in GitHub Desktop.
Admin Ajax Example
<?php
/**
* AJAX actions
*
* @since 1.0.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handle AJAX click tracking action
*/
function my_ajax_tracking_action() {
// AJAX Call
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
$response = false;
// DO WHATEVER YOU WANT AND MAYBE UPDATE $response VARIABLE
// response output
echo $response;
}
// IMPORTANT: don't forget to "exit"
exit;
}
add_action( 'wp_ajax_nopriv_my_ajax_tracking_action', 'my_ajax_tracking_action' );
add_action( 'wp_ajax_my_ajax_tracking_action', 'my_ajax_tracking_action' );
jQuery(document).ready(function ($) {
/**
* Handling the clicks
*/
$('[data-click-me="true"]').on( "click", function( event ) {
var postid = $(this).data('postid');
clickMeAction(postid);
});
/**
* Send AJAX request
* @param type
* @param couponId
*/
function clickMeAction( postid ) {
// Request
jQuery.ajax({
url : my_post.ajax_url,
type : 'post',
data : {
action : 'my_ajax_tracking_action',
postid: postid
},
success : function( response ) {
//console.log('Response: ' + response);
}
});
}
});
<?php
/**
* Load scripts
*
* @since 1.0.0
* @global string $post_type The type of post that we are editing
* @return void
*/
function my_scripts( $hook ) {
// Use minified libraries if SCRIPT_DEBUG is turned off
$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
wp_enqueue_script( 'my-script', MY_PLUGIN_URL . 'public/js/scripts' . $suffix . '.js', array( 'jquery' ), MY_PLUGIN_VERSION, true );
wp_localize_script( 'my-script', 'my_post', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment