Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active February 8, 2018 14:39
Embed
What would you like to do?
[WordPress] A basic example of how to setup Ajax on both the server-side and the client-side.
<?php
add_action( 'wp_enqueue_scripts', 'acme_add_ajax_library' );
/**
* Adds the WordPress Ajax Library to the frontend.
*
* @since 1.0.0
*/
function acme_add_ajax_library() {
wp_localize_script(
'ajax-script',
'acme_demo',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
);
}
/**
* Determines whether or not the user as voted on the current post. This is used
* in conjunction with the client-side to prevent users from continually voting on a
* post.
*
* If the post ID is not set in the $_GET collection, this function will return a -2
* to indicate that not post ID has been specified.
*
* @since 1.0.0
* @access private
*
* @param int $post_id optional The ID of the post to determine if the user has voted.
*/
function acme_user_has_voted( $post_id = '' ) {
// If the post ID isn't specified then retrieve it from the $_GET collection
if ( '' == $post_id ) {
// Make sure the post ID is set in $_GET
if ( isset( $_GET['post_id'] ) ) {
/* This might be a little aggressive for this exmaple, but it's shows
* why it's important to filter input coming from the client-side.
*
* ht @gmazzp
*/
$post_id = filter_input(
INPUT_POST,
$_GET['post_id'],
FILTER_SANITIZE_NUMBER_INT
);
} else {
wp_send_json_error(
new WP_Error( '-2', 'The post ID was not specified.' )
);
}
}
// Look to see if there's an IP for this review
$user_has_voted = ( '' !== trim( get_post_meta( $post_id, "versus_user_has_voted", true ) ) );
wp_send_json_success(
json_encode( $user_has_voted )
);
}
$.get( ajaxurl, {
action: 'acme_user_has_voted',
post_id: $( '#post_id.hidden' ).text()
}, function( response ) {
// Handle the response however best suits your needs
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment