Ajax in WordPress

WordPress logo

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>

25 thoughts on “Ajax in WordPress”

  1. Thanks for this post. I used your script and thought everything was fine. It works perfectly in Chrome, FF and Safari. However, I discovered that in all versions of IE, the post meta is not updating and the alert box pops up with 'ajax submitted' ... or in my case, 'If you are using Microsoft IE and can see this message, you need to download and use a current browser like Chrome, Safari or FireFox. Go UPGRADE now: http://www.google.com/chrome Internet Explorer is the Edsel of Internet Browsers. Just sayin!' But, I would rather it work in IE than display the alert. I have Googled this quite a bit and tried numerous attempts to fix the problem (the way IE handles event registration, and/or bubbling??). But none have worked. Any ideas on how to fix this?

    Reply
    • I posted a comment a few hours ago that is still awaiting moderation. I could have sworn this script was working in Firefox before. But, now I discovered it is not working in Firefox nor IE (all versions of IE ... at least 8,9 & 10). It works fine in Chrome and Safari though.

      Reply
      • Thanks for posting my comments. I was curious though if you have checked your code to see if it actually works on IE and Safari. I saw someone who posted earlier about just getting an alert box. I am guessing there is a good chance they were using IE; and never tried it in a better browser. Other than that the only thing substantially different in my code and yours is that I have two inputs (essentially, the user clicks on button that says YES, or they click on a button that says NO. So, instead of one update_post_meta, there are two. - Let me also clarify that the fact is that the meta is not actually being updated via Chrome or Safari. However, I am able to see the display change because my code echos $_POST['theinputfield'] instead of the variable for the get_post_meta($theinputfield) .... BTW, do you have a working example of your code?

        Reply
        • I am using this code in all my projects and it works in all modern browsers (including older IE versions). If you have an error in firefox - try to use firebug addon to find the problems in the code.

          Reply
          • Thanks for the response. I have used Firebug. But, there are no errors being generated. There are no breakpoints to deal with. I also checked error logs. Nothing there. Likewise, I tried using the IE Dev Tools, but there are no errors being returned. I don't have a lot of hair left to pull out. Odd ... no errors. But, the post meta is not being updated.

            Reply
  2. Thanks for the info. It was extremely helpful. Do you have any information on nounce. If I'm able, I'd like to make the my code secure.

    Reply
  3. 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...

    Reply
    • 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.

      Reply
  4. 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.

    Reply
      • 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.

        Reply

Leave a Reply to theBrettman Cancel reply