Skip to content

Instantly share code, notes, and snippets.

@w33zy
Last active May 5, 2021 15:00
Show Gist options
  • Save w33zy/949a95a7960d7202fe9bad4e3d93b77c to your computer and use it in GitHub Desktop.
Save w33zy/949a95a7960d7202fe9bad4e3d93b77c to your computer and use it in GitHub Desktop.
WP AJAX
jQuery(document).ready(function() {
jQuery("#the-empty-div").click(function(){
jQuery.ajax({
type: 'POST',
url: my_ajax_data.ajax_url,
data: {
action: 'my_ajax_action_callback',
security: my_ajax_data.security_nonce,
first_name: 'John', // Get this however
last_name: 'Smith', // Get this however
}
});
});
});
function ajax_login_init(){
if ( ! is_user_logged_in() || ! is_page( 'page-test' ) ) {
return;
}
wp_enqueue_script( 'my_script_handle', plugin_dir_url(__FILE__) . '/JS/script.js', array( 'jquery' ) );
wp_localize_script(
'my_script_handle',
'my_ajax_data',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'security_nonce' => wp_create_nonce( 'my-security-nonce' )
)
);
}
add_action( 'wp_enqueue_scripts','ajax_login_init' );
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );
function my_ajax_action_callback() {
check_ajax_referer( 'my-security-nonce', 'security' ); // Do not leave this out
$out = '';
$first_name = isset( $_POST['first_name'] ) ? sanitize_text_field( $_POST['first_name'] ) : 'N/A';
$last_name = isset( $_POST['last_name'] ) ? sanitize_text_field( $_POST['last_name'] ) : 'N/A';
$out .= '<p>Hello. Your First Name is ' . $first_name . '.</p>';
$out .= '<p>And your last name is ' . $last_name . '.</p>';
echo $out;
wp_die(); // required. to end AJAX request.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment