Created
February 4, 2016 16:17
-
-
Save chriswinch/e08f0bc7ca7fb4775d58 to your computer and use it in GitHub Desktop.
Wordpress Ajax Setup ( from http://www.bobz.co/ajax-filter-posts-tag/ )
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
function ajax_setup_scripts() { | |
// Register and Enqueue Script | |
wp_register_script('afp_script', get_template_directory_uri() . '/js/scripts.js', false, null, false); | |
wp_enqueue_script('afp_script'); | |
wp_localize_script( 'afp_script', 'afp_vars', array( | |
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), | |
'afp_ajax_url' => admin_url( 'admin-ajax.php' ), | |
) | |
); | |
} | |
add_action('wp_enqueue_scripts', 'ajax_setup_scripts', 100); | |
function ajax_setup( $vars ) { | |
// Verify nonce | |
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) | |
die('Permission denied'); | |
$vars = $_POST['vars']; | |
echo $vars; | |
die(); | |
} | |
add_action('wp_ajax_setup', 'ajax_setup'); | |
add_action('wp_ajax_nopriv_setup', 'ajax_setup'); |
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
jQuery(document).ready(function($) { | |
// data to pass to function | |
data = { | |
action: 'setup', // function to execute | |
afp_nonce: afp_vars.afp_nonce, // wp_nonce | |
vars: 'Data goes here', | |
}; | |
// pass data to function and log response | |
$.post( afp_vars.afp_ajax_url, data, function(response) { | |
if( response ) { | |
console.log(response); | |
}; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment