Simplified AJAX For WordPress Plugin Developers using Jquery

I am assuming you know how to write a WordPress plugin, and now you are wondering how to use ajax to add that sexy feature that will make your plugin look a bit kool.

I faced the same problem, with my akWpUploder plugin. I googled but could not find anything interesting, or should I say, simple way of adding ajax to my plugin. So I dig into the WordPress code base for solution, as auto-saving feature of WordPress was one such thing that I wanted to use.

There I found what I was really looking for, a very simple way of using Ajax to get things done.

Problem: How to use WordPress functions in your plugin when using ajax

Are you satisfied with your knowledge? No, then spent 15 minutes every day on PHPCamp a knowledge-sharing website for our own PHP community

Let me explain the problem first, while I was working on my plugin I needed to insert the photo data into the database. To do this I needed to use WordPress database functions, but the way I knew to use ajax(i.e. creating a separate PHP file that handles the ajax request), it was bit difficult and messy. It would have involved either making a direct connection with the database or including the WordPress config file.

I was not happy with either of these options, I needed a simpler solution.

Solution: admin-ajax.php and action hook wp_ajax_

As I mentioned earlier I dig into WordPress to see the way WP uses ajax to save the posts.

What I found was this code.

      default :
	do_action( 'wp_ajax_' . $_POST['action'] );
 	die('0');

So, now all I needed to do was send all my ajax requests to admin-ajax.php to provide an ‘action’ and WordPress will call the function attached to that hook.

Neat, isn’t it? Now I can keep my plugin simple.

Implementation: an example

You might be thinking “It’s ok, but can you show me an example?”

Yeah, sure I will.

First we take care of javascript, here I am using Jquery, the easiest javascript library available.

  1. Let’s include jquery:
    <?php
    echo'<script src="'.get_option('siteurl'). '/wp-content/plugins/jquery-1.2.3.min.js"> </script>';
  2. Now the code for ajax request: there are two things to notice
    1. the ‘action‘, which contains the value to be used with ‘wp_ajax_‘ to make a WordPress hook.
    2. the other is ‘cookie‘ which contains the cookie required to authenticate your admin access to admin-ajax.php.
    <script>
     $.post(siteurl+"/wp-admin/admin-ajax.php", {action:"ak_attach", 'cookie': encodeURIComponent(document.cookie)},
     function(str)
    {
          alert(str);
    });
    
    </script>

With this the javascript part of the things is over.

Now we will take care of handling this request in our plugin.

  1. So first we will create the function that will respond to ajax request. you should notice that i have used the exit at the end this is because i want the script to end here, other wise i will get ‘0’ with my data.
    <?php
    function ajaxResponse(){
    global $wpdb; 	global $userdata;
    get_currentuserinfo();
     echo "Hello ". $userdata->user_login;
     exit;
     }
  2. Now we need to tell wordpress about this function, so we will attach this function to the Hook that we created, by providing the action parameter in the javascript code above.
     add_action('wp_ajax_ak_attach', 'ajaxResponse');
    add_action( ‘wp_ajax_nopriv_ak_attach’, ‘ajaxResponse’ );//only used for non-loggedin scenario

That’s it we are done.

Now that you know how to use ajax easily while writing the your plugin, go ahead and use it. Download code for this demo plugin which shows the whole operation, and can act as template.

Note: admin-ajax.php only allows admin users to post the data, which means this can only be used on admin area of wordpress and not in the general scenario. For using ajax in other situations please check Using AJAX with your WordPress Plugin tutorial by Ronald.  With the latest version of WordPress, it is possible to use admin-ajax.php for all situations.

Comments

51 responses to “Simplified AJAX For WordPress Plugin Developers using Jquery”

  1. […] wordpress config file. I was not happy with either of these options, I needed a simpler solution.read more | digg story Share and Enjoy: These icons link to social bookmarking sites where readers can […]

  2. phil.gs Avatar

    That is very cool. I had used a file in the plugin directory that linked back to and included the wp-config file. I will have to try this method when I get a chance.

  3. gate correspondence Avatar

    That is very cool. I had used a file in the plugin directory that linked back to and included the wp-config file. I will have to try this method when I get a chance.

  4. […] Simplified AJAX For WordPress Plugin Developers using Jquery(10APR0 […]

  5. sikiş Avatar

    thanx man

  6. […] wasn’t sure exactly how to go about it. So after a search, I found this great explanation: Simplified AJAX For WordPress Plugin Developers using Jquery. But it stops short of explaining how to receive some data from a POST, give it to PHP to do […]

  7. […] Simplified ajax for WordPress plugin developers […]

  8. […] Simplified ajax for WordPress plugin developers […]

  9. Ricky Avatar

    Hey, Thanks for the writing this post. This was exactly the problem I was having. After your page I also found some others WordPress AJAX examples using jquery here:

    http://ocaoimh.ie/2008/11/01/make-your-wordpress-plugin-talk-ajax/

  10. Tyler Avatar

    Hi,

    Thanks for this article, I’m just looking for how to do this in my plugin, and your article help me a lot. Thankss!

  11. memulai bisnis online Avatar

    nice, I’ll try and use it in my current project. Thank you.

  12. […] WordPress Eklenti Geliştiricileri İçin Basitleştirilmiş AJAX […]

  13. Waterman pens Avatar

    Woww, Thank you brother . Very good theme .

  14. […] promised here is a list of some plug-in development resources: Simplified AJAX For WordPress Plugin Developers using Jquery “Desenvolvendo Plugins para WordPress” by Rafael Dohms (in Brazilian Portuguese) 12 […]

  15. […] WordPress Eklenti Geliştiricileri İçin Basitleştirilmiş AJAX […]

  16. Michael Avatar

    Great post, I found this very useful for the WP site I am currently in development with.

  17. Jonah Goldstein Avatar

    cool.

    I was wondering how I could hook into the wordpress, built-in DB functionality… had copped out with some direct DB calls (sloppy). good job digging into the wordpress core and figuring it out – and especially thanks for sharing:)

    ciao

  18. fan Avatar

    goood post…wordpress is the best…

  19. LacnyWebHosting Avatar

    Great article, adding it to my bookmarks!

  20. […] Simplified AJAX For WordPress Plugin Developers using Jquery […]

  21. Samuel Avatar

    This only works if the user is logged in, otherwise, wordpress returns a -1 and never gets into the function.

  22. […] Simplified AJAX For WordPress Plugin Developers using Jquery […]

  23. […] Simplified AJAX For WordPress Plugin Developers using Jquery […]

  24. babu Avatar

    thanks for your details

  25. rcanblog Avatar

    Great post, I was looking for something like this for my new plugin.

    Thanks

  26. Brad Avatar

    Thanks for the tutorial, it cleared up some of my issues with using ajax in the admin.

    -Brad

  27. […] Simplified AJAX For WordPress Plugin Developers using Jquery | am … 10 Apr 2008 … How to use WordPress functions in you plugin when using ajax. amiworks.co.in/…/simplified-ajax-for-wordpress-plugin-developers-using-jquery/ – Cached – Similar […]

  28. Darsain Avatar

    You can use admin-ajax.php for no-admin actions, you just need to change the start of the hook from “wp_ajax_” to “wp_ajax_nopriv_”

  29. Redgie Avatar

    Nice article but I am looking to go to a page which has a dropdown box and when the user selects the race from the drop down box the results will be displayed below it. Any help on how to do this would be much appreciated

  30. […] Simplified AJAX For WordPress Plugin Developers using Jquery […]

  31. Kathy Avatar
    Kathy

    if you develop a plugin that relies on AJAX, what (if anything) do you do as a failsafe for people who have javascript disabled?

  32. Stefan Avatar

    Thanks for the explanation. Every time I search for that I keep coming back and though I forget everytime I directly remember how that Ajax-thingy works with wordpress.

    Good work. Thanks
    Stefan

  33. career outlook Avatar

    This is a great post, it will really going to help the many wordpress developers…thanks a ton 🙂

  34. Filip Avatar

    Thank you, this is great stuff.

  35. Dasha Avatar

    Hello, thanks for the post.

    I’ve got the demo version. I’m new to WP and ajax… I have some difficulty in understanding what the line add_action(‘edit_form_advanced’, ‘ajaxDemo’) does. Could you explain it a bit more?

    Thanks:)

  36. Dasha Avatar

    Hm… I see that add_action(‘edit_form_advanced’, ‘ajaxDemo’) adds a button at the bottom of the edit screen for any kind of post – WP post or a custom post type.

    I have a CD post type where I’d like to use ajax to add as much tracks to it as I want. Can I tire up the ajax only to a specific metabox? so it appears only in the CD posts when creating or editing CD info?

    Would really appreciate any help!

    Thanks,
    Dasha

  37. akeanant Avatar

    Very nice solution.

  38. wordpress elite Avatar

    Great stuff for plugin development, I’m just wondering using <a href="http://wpleet.com/wordpress-ajax-jquery-practice-using-shortcode/&quot; wordpress and ajax in your post.

  39. Görkem Avatar

    Very nice solution.Thanks

  40. […] you are a jQuery developer, Simplified AJAX For WordPress Plugin Developers using Jquery should be what you need. This tutorial explains how to use ajax to add that sexy feature which will […]

  41. […] Simplified AJAX For WordPress Plugin Developers using Jquery | am i works? […]

  42. Frank Indelicato Avatar
    Frank Indelicato

    Thank you. You explained it very well and the plugin clarified it all. I was looking for a way to dynamically populate an HTML select box from the wpdb. After modification this will work great!

  43. […] Common Coding Mistakes in WordPress Plugins WordPress 2.0.3: Nonces (Secure your forms with nonces) Simplified AJAX For WordPress Plugin Developers using Jquery “Desenvolvendo Plugins para WordPress” by Rafael Dohms 12 part “How to Write a […]

  44. Wordpress Elite Avatar

    Bookmarked! Thanks for this article. This inspired me to create a useful article on WordPress AJAX. I also included in the article on how to combine WordPress Shortcode and AJAX for easy implementation on your WordPress blog.
    http://wpleet.com/wordpress-ajax-jquery-practice-using-shortcode/

  45. Eric Uned Avatar

    Thanks for the plugin! I´ve finally found it.
    Thats what i was looking for.

    Kind regards!!

  46. […] Simplified AJAX For WordPress Plugin Developers using jQuery(10APR08) […]

  47. […] Simplified ajax for WordPress plugin developers […]

  48. […] Simplified AJAX For WordPress Plugin Developers using Jquery(10APR08) […]

  49. pankaj Avatar
    pankaj

    Hey,
    I have more than 1 echo statement in my ajax function. So the alert box is not showing up anything.(function(str){alert(str);}).
    How can i fix this issue