[WordPress] A basic example of how to setup Ajax on both the server-side and the client-side.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ) | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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