Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Using Ajax in Your Plugin and WordPress Admin

Posted on June 15, 2012 by Pippin in Advanced, Ajax, Free Members, Member Restricted, Tutorials, Video Tutorials, WordPress Admin / Dashboard, Working with jQuery, Writing Plugins 37 Comments
Home» Tutorials » Advanced » Using Ajax in Your Plugin and WordPress Admin
Tweet
Love It - 14

This video tutorial walks you through the process of using ajax in the WordPress admin within your own plugins. The end result of this tutorial is not a complete plugin, but it does show the entire process, step by step, of how ajax is utilized in the WordPress dashboard.

Unlike most of my tutorials, I do not use any pre-existing plugin or code as reference during the video; it is all coded live during the video, so mistakes and small bugs are common, but they really help to illustrate issues that developers often encounter while working with ajax.

The complete source code for this tutorial is free to download below if you are logged in.

You must be logged in to view the rest of this content. Register or login from the sidebar.

Tweet Follow @pippinsplugins
add_options_page, Ajax, wp_enqueue_script, wp_localize_script

37 comments on “Using Ajax in Your Plugin and WordPress Admin”

  1. paul says:
    June 16, 2012 at 7:20 am

    thanks Pippin, that was really helpful!

    Have you tried Netbeans or PhpStorm IDE? Curious about why you are using Bluefish.
    Also, do you use xdebug? I find it really helpful to live debug.

    Reply
    • Pippin says:
      June 16, 2012 at 9:47 am

      Yep, hated them both. I personally really like Bluefish, and other super light weight non-IDE editors. My favorite editor of all time is Notepad++, but it doesn’t run on Linux.

    • poifox says:
      June 16, 2012 at 1:13 pm

      Excellent tut! :)

      Eclipse + Aptana 3 is awesome for PHP dev, super fast and the code completion is super powerful. Saves me tons of time writing core PHP functions and any other function from WP or the framework I’m working with (when you include the wp-* in the build path of the project).

    • poifox says:
      June 16, 2012 at 1:16 pm

      Also when setup correctly, and you may want to know what the function does exactly you just position the caret on the function and hit F3 and Eclipse opens the function declaration, whereever it may be located inside WP :)

    • Pippin says:
      June 16, 2012 at 1:30 pm

      I tried to use Eclipse/Aptana for a few days and couldn’t get comfortable with it. It just didn’t seem to work well for me.

    • Jun Pratama says:
      January 9, 2013 at 3:39 pm

      Same here, I like notepad++. And you can use it with Linux as well. It will run perfectly with “wine” program.

  2. Jack says:
    June 16, 2012 at 10:48 am

    +10 for Notepad++

    Reply
  3. riskiii says:
    June 18, 2012 at 6:06 pm

    You might try sublime text 2. It runs on linux.

    Reply
    • Pippin says:
      June 18, 2012 at 6:07 pm

      I will give it a shot, though, as you can tell above, I’m very picky :)

    • Johnny Bridges says:
      June 25, 2012 at 7:21 am

      +1 for Sublime Text 2.

      EPIC editor, you can use also use most Textmate bundles with it.

      Must have install – http://wbond.net/sublime_packages/package_control

  4. joacim says:
    June 27, 2012 at 4:39 pm

    Yeay! Could you do more stuff with this? like those checkboxes you’ve talked about at the end :) would be great.

    Reply
    • Pippin says:
      June 27, 2012 at 5:53 pm

      I will try :)

    • joacim says:
      June 28, 2012 at 1:47 am

      Sweet :D

  5. Patrick Miravalle says:
    July 8, 2012 at 10:19 pm

    I have been wanting to learn more about using AJAX with WordPress for a while now, and this tutorial has definitely given me a great foundation to work off of and to learn from. Thanks Pippin!

    Reply
  6. 69developer says:
    August 25, 2012 at 8:14 am

    I think there may be an error in the code where your doing nonce verification. You mentioned in the video you forget the proper setup of the wp_verify_nonce and you look at the codex to make sure.

    In your video you have the $nonce and $action backwards, I think?

    Reply
    • Pippin says:
      August 25, 2012 at 8:56 am

      Yep, it’s very possible I did them backwards. The action should be first and the nonce second.

  7. M@rc says:
    August 31, 2012 at 5:40 pm

    Thank you for this introduction to using ajax with WordPress, one of the best I’ve seen on the subject. It was very helpful to me. I am running into an issue however. I successfully used this on a meta box that has an input for searching post titles. After submitting the search, results get placed in an empty div just like you showed in your tutorial. But I would like to add another ajax call after the first one has displayed the search results, which should fetch basic info from a post when you click a search result. The problem is when I click on one of the results, nothing happens, even though I verified that the ajax is working. It looks like the jquery is not responding to the click event I added to the post title. Actually I am doubtful jquery even sees the post title that was inserted into the DOM via ajax, preventing me from targeting the post title?

    Am I doing this the wrong way? Is there a preferred way of handling multiple ajax calls in succession I should be aware of?

    Reply
    • M@rc says:
      September 1, 2012 at 2:49 pm

      I fixed my problem: turns out using the .click jquery event was not responding on a handler that was generated with ajax. Solution is here: http://stackoverflow.com/questions/9344306/jquery-click-doesnt-work-on-ajax-generated-content

    • Pippin says:
      September 1, 2012 at 9:41 pm

      Yep, that’s the answer. Sorry for being a bit slow.

  8. locusuk says:
    November 20, 2012 at 12:29 pm

    Pippin
    Thank you for a great video article. I am embarking on the use of Ajax in my plugins for the first time and found this very helpful.
    I do however hope you can help me with something that is probably very simple, but I have not yet been able to resolve.
    I have managed to recreate your example for the use of Ajax on the admin side, but I am looking to replicate the idea on the frontend.
    I have tried to look it up and found the information, but cant seem to get it to work.
    I have reproduced the form and button your created within a shortcode function for display on a page, and also localized the admin-ajax.php script with the following code.
    wp_localize_script('WP-Ajax', 'ttftajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    I have also added the required nopriv within the add_action code.
    add_action ('wp_ajax_nopriv_TTET_Get_Front_Results', 'TTET_Process_Frontend_Ajax');
    The button works as expected, but the page refreshes. I have not been able to find out why. Looking up the problem I have found that the return false; statement at the end of the java script should prevent this, but for some reason it does not.
    Can you help at all?
    Thanks
    Colin

    Reply
    • Pippin says:
      November 20, 2012 at 3:58 pm

      Hi Colin,

      Can you show me examples of your code?

  9. locusuk says:
    November 21, 2012 at 12:55 pm

    Pippin

    Thank for getting back to me.
    This first section is the plugin file (excluding plugin headers)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    
    //Load Ajax Scripts For Admin
     
    function TTET_Load_Ajax_Frontend_Scripts(){
     
    	wp_enqueue_script('TTET-Ajax-Frontend', plugin_dir_url(__FILE__) . 'js/TTET-Ajax-Front.js', array('jquery'));
    	wp_localize_script('TTET-Ajax-Admin', 'TTET_vars', array('TTET_nonce' => wp_create_nonce('TTET_nonce')));
    	wp_localize_script('WP-Ajax', 'ttftajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    	wp_enqueue_script( 'json-form' ); 
    }
     
    add_action('wp_enqueue_scripts', 'TTET_Load_Ajax_Frontend_Scripts');
     
     
    //Populate Frontend Page Content Through Shortcode
     
    function TTET_Ajax_Frontend_Content(){
    global $TTET_Ajax_Settings;
    	?>
     
    			220810 Ajax Demo
     
     
    				<img id="TTET_Ajax_Loading" src="" class="waiting" style="display:none;">
     
     
     
    	<?php
    }
     
    add_shortcode("TTET_Ajax_Front", "TTET_Ajax_Frontend_Content");
     
     
    // Process Ajax Request
     
    function TTET_Process_Frontend_Ajax(){
     
    	if( !isset( $_POST['TTET_nonce'] ) || !wp_verify_nonce($_POST['TTET_nonce'], 'TTET_nonce')){
    		echo 'Permision Check Failure'; die();}
     
    	$TTET_Results = get_posts(array('post_type' => 'page', 'posts_per_page' => 10));	
     
    	if ( $TTET_Results ) :
     
    		echo '';
     
    		foreach($TTET_Results as $TTET_Result) {
     
    		echo '' . get_the_title($TTET_Result->ID) . '';
     
    		}
     
    		echo '';
     
    	else :
     
    		echo 'No Results Found';
     
    	endif;
     
    	die();
     
    }
     
    add_action ('wp_ajax_nopriv_TTET_Get_Front_Results', 'TTET_Process_Frontend_Ajax');

    and the following is the JS file

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    jQuery(document).ready(function($){
    	$('#TTET-Ajax-Form').submit(function(){
     
    		$('#TTET_Ajax_Loading').show();
     
     
    		data = {
    			action: 'TTET_Get_Front_Results',
    			TTET_nonce: TTET_vars.TTET_nonce
    		};
     
    		$.post(ttftajax.ajaxurl, data, function (response) {
    			$('#TTET_Results').html(response);
    			$('#TTET_Ajax_Loading').hide();	
     
     
    		});
     
     
     
    		return false;
    	});
    });

    I hope you can help me find what is probably staring me in the face.
    Thanks
    Colin

    Reply
    • Jonthan Acosta says:
      November 21, 2012 at 4:09 pm

      locusuk, you have to prevent default right after the event is passed to
      $(‘#TTET-Ajax-Form’).submit(function(){});

      like this:

      $(‘#TTET-Ajax-Form’).submit(function(e){
      e.preventDefault();
      });

      That will stop the browser from reloading the page but execute the ajax request on form submission.

    • Pippin says:
      November 21, 2012 at 5:09 pm

      What Jonathan said is correct.

  10. locusuk says:
    November 22, 2012 at 2:25 pm

    @Jonthan Acosta and Pippin

    Thank you for you help. That sorted my problem. I thought it would be something simple.
    My one question is though, how come preventDefault(); was not required in the admin based version as per the video article?
    Thanks
    Colin

    Reply
    • poifox says:
      November 22, 2012 at 3:55 pm

      @locusuk I really don’t know, since your code seems pretty much the same as the tutorial’s. in my experience doing e.preventDefault(); first and doing all your logic afterwards is more reliable.

      Also using $.ajax({url:”",data:{},success:function(){},error:function(){}}) is also easier to debug although it could potentially make you write more code, but more debuggable.

  11. Omprakash says:
    December 13, 2012 at 8:40 am

    Nice Tutorial Really that will help everyone for doing ajax in wordpress. But i think if you provide sample demo of the code then it will be better.

    Reply
  12. ifarhan says:
    December 13, 2012 at 11:18 pm

    This plugin tutorial is really nice, easily show how we implement AJAX in our custom Plguin.
    Really Love this tutorial
    Thanks Pippins.

    Reply
  13. Samrat Khan says:
    February 13, 2013 at 3:41 am

    An extra plus (+) for Notepad++, so it becomes Notepad+++, i like Notepad ++

    Reply
  14. Barry Laminack says:
    March 26, 2013 at 11:02 pm

    Is there anything else that should be done to run this on a submenu of a plugin? I did the tutorial and it worked fine as a stand alone plugin that is accessed via the settings area. But when I tried to do this in my custom plugin on a submenu page using the same exact code (with updated paths) all I get is 0 when I click the button.

    Reply
    • Pippin says:
      March 27, 2013 at 10:01 am

      No, it shouldn’t be any different.

  15. luckdragon says:
    April 23, 2013 at 6:31 pm

    I’m trying to create a popup window (using highslide) that updates the data on the screen via ajax.. I know how to update the datatables and all that via ajax (with some help from your tutorial), but I was wondering if you know which file I need to include into the external php for the highslide window (I don’t need all of the admin area layout, just the database and wp function/connections)

    thank you in advance

    Reply
    • Pippin says:
      April 24, 2013 at 9:26 am

      That shouldn’t be done in an external file. It’s generally a bad idea to manually include core WP files in order to gain access to WP functions.

    • luckdragon says:
      April 25, 2013 at 6:25 am

      that’s why I’m asking for advice on how to do it :) I like the look/feel of the highslide window, but don’t know if in addition to the ajax stuff I can put into wp, if there is a “popup” definition that doesn’t display all of the template stuff (I want to keep the styling, but basically it will just be a form on a white background with no header or menu,etc…)

  16. Andy Hodges says:
    April 28, 2013 at 6:50 pm

    Thank you for the post it seems to have a long life.

    I am looking at the codex for the difference in treatment of the AJAX script file in admin and elsewhere and struggling to find it. Any pointers?

    While I am here why on earth does WordPress feel the need to append the version number to the script? Is this part of its own encoding? (ajax.js?ver=3.5.1[from rendered source code])

    and thanks for dealing with the replies to everyone most helpful.

    Reply
    • Pippin says:
      April 29, 2013 at 10:56 am

      The version numbers are appended for caching reasons. See this post: http://pippinsplugins.com/uncached-script-and-style-updates/

  17. Rob says:
    May 8, 2013 at 1:48 pm

    Wonderful tutorial!

    Thank you so much – I’m new-ish to plugin dev and this was thoroughly enlightening. Please keep up the good work!

    R

    Reply

Leave a Reply Cancel 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>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Ensure Your Scripts and Styles Are Not Cached with Updates
  • Create a Live Search in WordPress with jQuery and Ajax
  • Loading Scripts Correctly in the WordPress Admin
  • WordPress Rewrite API – Part 3
  • Love It Pro for WordPress

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (2)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • @digitalFocus I&#039;m done for the day but can chat tomorrow
    May 23, 2013
  • @digitalFocus Send me an email and we can try to schedule a time
    May 22, 2013
  • RT @elliott_stocks: Using @eddwp ? Checkout the Custom Prices (aka name your price) extension! https://t.co/78f8ordkNB #WordPress
    May 22, 2013

Topics

hook meta box Rémi Corson featured shortcodes campaign monitor add_options_page register_setting Sugar Event Calendar attachments add_shortcode wp_enqueue_script the_content image forms short codes Related posts login do_action authors mail chimp attachment plugin recent posts comments post types bbpress apply_filters short code taxonomies custom post type Ajax images gallery Stripe jquery taxonomy users widgets add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2011 Pippin's Plugins