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
 
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( '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
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
}
?>

"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>
VN:F [1.9.17_1161]
Rating: +2 (from 2 votes)

13 thoughts on “Ajax in WordPress

  1. it should be noted that ajaxurl is already defined in the header of admin pages but your localize_script example is needed on the frontend. thanks for the updated article though. It helped me out. some of the other articles linked to on the codex are very outdated and cause confusion and should be removed. I might make my own articles with more examples to help out when I'm done with this project. ajax nonces is a lacking subject...

    VA:F [1.9.17_1161]
    Rating: 0 (from 0 votes)
    • I updated page about ajaxurl in admin pages. You can read more about nonces in WordPress and ajax on page, link to this article is on the top of this page. I create this article for having lite code for copy-paste it into WP projects. If you will write better article or write feedbacks about this one it would be awesome.

      VN:F [1.9.17_1161]
      Rating: 0 (from 0 votes)
  2. Hi,

    I followed instructions and I get the alert box. Great!

    But I'm trying to load the #content of the target url into the current #content div. How can I do that?

    Many thanks for your help.

    VA:F [1.9.17_1161]
    Rating: -1 (from 1 vote)
      • Thanks for the quick answer. I'm sorry but nothing is returned on click (testing with alert(data);), could you include a quick example.

        Added the following to functions.php:

        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 $content;
        die(); // stop executing script
        }
        ?>

        I would also like to know where I can get the list of available variables I can use... Thank you for your time and help.

        VA:F [1.9.17_1161]
        Rating: 0 (from 0 votes)
          • This article doesn't use admin-ajax.php and the method you described above. My theme is pretty much ajaxified. I just need to know how to retreive the information. The handler is ready. ;-)

            But nevermind, I'll search a bit more... Thanks

            VA:F [1.9.17_1161]
            Rating: 0 (from 0 votes)
  3. Pingback: P’SEC: Connecting Dots, Part V « David Seah / Code

  4. Pingback: P’SEC: Connecting Dots, Part IV « David Seah / Code

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">