Simplified AJAX For WordPress Plugin Developers using Jquery

April 10th, 2008 | Save to del.icio.us now(0)

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 which will make your plugin look 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 you plugin when using ajax

Are you satisfied with your knowledge? No, then spent 15 minutes every day on PHPCamp.net 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 which 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 request to admin-ajax.php 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: their 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 you 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');

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.

Related posts

  1. Fix ‘Blank page’ problem aka White Screen of Death
  2. Where is MySQL Gone Away?
  3. Simple JavaScript ‘Frame Busting’ Code
  4. How to use SVN and Git together to get the best of both worlds in Windows
  5. How to Remove Antivirus XP 2008

Wondering what to do next?


(Search web development related contents)


30 Responses to “Simplified AJAX For WordPress Plugin Developers using Jquery”

  1. April 10, 2008 1:16 pm Simplified AJAX For WordPress Plugin Developers using Jquery | White Sands Digital says

    [...] 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. April 10, 2008 1:37 pm phil.gs says

    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. July 10, 2008 10:24 am gate correspondence says

    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. July 15, 2008 8:31 pm Wordpress Tutorial « Welcome To My BLOG says

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

  5. July 30, 2008 8:47 am sikiş says

    thanx man

  6. October 23, 2008 1:30 am Ryan Pharis - Lubbock, Texas Web Designer & Developer, WordPress Consultant » Blog Archive » Ajax for WordPress Plugins Using jQuery says

    [...] 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. December 30, 2008 7:19 am The Ultimate Guide to Building a Wordpress Plugin - NETTUTS says

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

  8. January 3, 2009 9:08 am Cotton Rohrscheib - Blog Archive » Building a Wordpress Plugin says

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

  9. January 15, 2009 11:20 pm Ricky says

    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. January 17, 2009 8:22 pm Tyler says

    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. February 6, 2009 1:03 pm memulai bisnis online says

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

  12. March 16, 2009 4:13 pm » wordpress eklentisi oluşturma rehberi says

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

  13. April 1, 2009 1:34 pm Waterman pens says

    Woww, Thank you brother . Very good theme .

  14. April 7, 2009 1:56 am WordPress Plugin Development Workshop at RMI - Recap | dropthedigibomb.com says

    [...] 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. May 20, 2009 6:17 pm WordPress Eklentisi Oluşturma Rehberi | Webmaster Arşivi | Script Download | Tema Download says

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

  16. July 17, 2009 3:22 am Michael says

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

  17. August 4, 2009 4:29 am Jonah Goldstein says

    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. August 12, 2009 9:10 pm fan says

    goood post…wordpress is the best…

  19. October 2, 2009 8:12 pm LacnyWebHosting says

    Great article, adding it to my bookmarks!

  20. October 6, 2009 12:01 pm skriv et plugin til wordpress - Ressourcer | 'Lær det via internet' says

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

  21. October 8, 2009 12:38 am Samuel says

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

  22. October 9, 2009 2:13 pm Essential Wordpress Plugin Development Resources, Tutorials and Guides : Speckyboy Design Magazine says

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

  23. November 4, 2009 7:31 am PHP Quebec Presentation | dropthedigibomb.com says

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

  24. November 16, 2009 6:14 pm babu says

    thanks for your details

  25. December 23, 2009 5:35 pm rcanblog says

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

    Thanks

  26. January 1, 2010 4:35 am Brad says

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

    -Brad

  27. May 5, 2010 2:27 pm wordpress plugins says

    [...] 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. May 6, 2010 10:21 pm Darsain says

    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. May 21, 2010 10:11 pm Redgie says

    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. July 3, 2010 2:00 am Kathy says

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

Trackback URI | Comments RSS

Say Something, and Be Counted

Name (required)

Email (required)

Website

Speak your mind