Ajax in WordPress

WordPress logo

Article about ajax in WordPress.
jQuery will be included automatically.
"ajaxurl" is already defined in the header of admin pages.
PHP code (could be in functions.php or in plugin):

<?php
function enqueue_scripts_styles_init() {
	wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/js/script.js', array('jquery'), 1.0 ); // jQuery will be included automatically
	// get_template_directory_uri() . '/js/script.js'; // Inside a parent theme
	// get_stylesheet_directory_uri() . '/js/script.js'; // Inside a child theme
	// plugins_url( '/js/script.js', __FILE__ ); // Inside a plugin
	wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
}
add_action('init', 'enqueue_scripts_styles_init');
 
function ajax_action_stuff() {
	$post_id = $_POST['post_id']; // getting variables from ajax post
	// doing ajax stuff
	update_post_meta($post_id, 'post_key', 'meta_value');
	echo 'ajax submitted';
	die(); // stop executing script
}
add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action_stuff' ); // ajax for not logged in users
?>

"script.js" javascript file:

jQuery(function($){
	$('.target').click(function () {
		$.post(ajax_object.ajaxurl, {
			action: 'ajax_action',
			post_id: $(this).find('input.post_id').attr('value')
		}, function(data) {
			alert(data); // alerts 'ajax submitted'
		});
	});
});

HTML code:

<div class="target">click me <input type="hidden" value="77" class="post_id" /></div>

You may contact via feedback form.