WordPress jQuery AJAX example

/**
 * WordPress jQuery AJAX example.
 *
 * @see https://wpcodebook.com/wordpress-jquery-ajax-example/
 */
add_action( 'wp_footer', function () {
	?>
	<script>
	jQuery( document ).ready( function () {
		jQuery.ajax( {
			type:     'POST',
			dataType: 'json',
			url:      '<?php echo admin_url( 'admin-ajax.php' ); ?>',
			data:     {
				action: 'wpcodebook_ajax',
			},
			success:  function ( msg ) {
				alert( msg );
			},
		} );
	} );
	</script>
	<?php
} );

/**
 * AJAX action for logged-in users.
 *
 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_action/
 */
add_action( 'wp_ajax_' . 'wpcodebook_ajax', function () {
	echo json_encode( 'response-example' );
	die();
} );

/**
 * AJAX action for logged-out users.
 *
 * @see https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv_action/
 */
add_action( 'wp_ajax_nopriv_' . 'wpcodebook_ajax', function () {
	echo json_encode( 'response-example-nopriv' );
	die();
} );

Leave a Comment