Using AJAX in WordPress Development. The Quick-and-Dirty QuickStart Guide

Edit: Enjoyed this? Check out my new post on AJAX using JSONP in WordPress.


There are some great posts and a fantastic wiki page explaining how to use AJAX in WordPress. But I haven’t found a quick plug-and-play tutorial. So here goes…

The problem: A simple form that will give the visitor an input and when they click “Next” it will send the content of the input to the server who will send all the $_POST fields back as JSON. Why you’d want this? Who knows. But it’s a simple problem to solve that you can adopt to do anything.

Here’s the Gist

This is the plug-and-play version my friends. (Extra points if you recognize what ui framework is here… DON’T JUDGE ME IT’S ONLY FOR WIREFRAMING.)

How to use the code

  • Add include_once('inputtitle_submit_inc.php'); in functions.php. Make sure inputtitle_submit_inc.php in in your template folder.
  • page-ajax_input.php is a template page, make sure it’s in in your template folder. Just create a page in WordPress using “Input Submition Page”.
  • inputtitle_submit.js should be in a folder named ‘js’ in your template folder. Otherwise

wp_enqueue_script( 'inputtitle_submit', get_template_directory_uri() . '/js/inputtitle_submit.js', array( 'jquery' ));

will fail.

How it works

page-ajax_input.php

This is a simple template file. The important elements here are the input field and the next button. They are hooked in the JS file.

inputtitle_submit_inc.php

The server-side magic.

The first line enqueues the js file and pops some variables in for the AJAX onto the page. They are called in inputtitle_submit_scripts().

The next two lines enable the AJAX to work. They create the ajax action “ajax-inputtitleSubmit”. If you only have “wp_ajax_ajax-inputtitleSubmit” it will only work for logged in users. If you only have “wp_ajax_nopriv_ajax-inputtitleSubmit” it will only work for logged out users. If you do this, make sure you have serious security in place.

Those two lines tie the action to myajax_inputtitleSubmit_func(). This is what happens server side. Inside you’ll find some nonce magic for security. The function checks the nonce, then converts the $_POST variables to JSON and sends them back to the browser. Don’t forget the exit();

inputtitle_submit.js

The Javascript.

First I encapsulate the JQuery so that it won’t conflict with anything. Then when the DOM is ready…

When “Next” is clicked it sends a POST AJAX request to the server. The AJAX URL was defined in wp_localize_script in inputtitle_submit_inc.php as well as the nonce.

We send the action, the nonce and the inputted “title” as variables to the server. Then in outputs the response (all $_POST variables as JSON) in the console.

Summary

I built this for reference sake. If you can suggest any best practices or improvements please comment below.


    33 thoughts on “Using AJAX in WordPress Development. The Quick-and-Dirty QuickStart Guide

    1. You, Sir, are a gentleman and a scholar =)
      I’m just getting into WP theme creation and I’m sure this will come in handy..

    2. Good tutorial, I’ve been trying to work out how to attach the similar action to a post thumbnail so when clicked a div is populated with the post content? I’m sure its only a few little changes but just cant seem to work it out :(

    3. hey Jack… trying to work out the WP-AJAX thing

      at the end of your article you mention “your template folder” and “your theme folder”

      are those the same folder?

      I’m doing a child theme off of twenty twelve and don’t see a template folder

      thanks for your help

    4. Hey – I just wanted to express my HUGE thanks for this line.

      include_once(‘inputtitle_submit_inc.php’); in functions.php.

      I’m new to WP and have FOUGHT for hours for this.

    5. I’ve tried your code (whilst learning) in one of the standard themes. I’m now trying to use it (again while learning) in a plugin. I’ve put the PHP & html in one script, & the js in another. The html is in a shortcode. I changed

      function( response ) {
      console.log( response );

      for

      function(response) {
      alert(response);

      When I click the next button after entering a value, I get [object object] in the alert box. Have you got any suggestions please? It would be really appreciated!

      1. Sure thing!

        Sounds like you’re getting the response, and object, but the alert isn’t parsing it right.

        Switch out the alert with a console.log and then open up the console in your browser’s dev tools.

        1. Thank-you. I’ve just done what you’ve told me to do, & it’s fine in the console log. Now, I just need to make it display the title in an alert.

          Thanks so much!

          1. Two ways to do this:
            1) Send only the string you want from the server. I.e. Echo $title; exit();
            2) alert out the specific data instead of the whole object you receive. Alert(response.title);

            1. Hi, Jack. Thanks for the tutorial. In response to your last comment, the latter works fine for me, but echoing $title from the server returns null in the console. I can see how it’s broken down in the console when I echo $response to the console, but I cannot figure out how to break it apart on the server side so I can pass my conditional arguments. I’ve tried looking for $response[‘title’], $response->title, and just $title. What am I missing? Thanks for your time.

    6. As usual, I figured it out a few minutes after posting the question.

      Have to do:

      $response = json_encode( $_POST[‘title’] );
      //then
      echo $response;

      Thanks again. Big help this.

    7. One more question, Jack. I’m trying to get the server to return HTML (that’s what I’m really in this for). I’ve tried setting the dataType to HTML on the script page, but no HTML will return. If it’s anything more than a single string, it won’t return from the server. Even if I just try combining two strings with $var .= $var2, it won’t return that. Any ideas how I can adapt your function to allow big chunks of php generated html? Thanks again!

    8. OH and by the way. I just had to adjust your iFrame height using Firebug in order to be able to see the submit button. FYI. :)

      Well I got the html to return finally, but not sure how. Just a bunch of aimless fiddling. Here’s how it’s set anyway:

      PHP:

      $path = json_encode( $_POST[‘pathpart’] );
      // bunch of arguments in php, generating html
      $response = json_encode($build);
      header( “Content-Type: application/json” );
      echo $response;
      exit;

      JQUERY/AJAX:

      (function($) {
      $(document).ready(function(){
      $(‘select#ghsc-upload-directories’).on(‘change’, function(){
      $.post(
      PT_Ajax.ajaxurl,
      {
      action : ‘ajax-inputtitleSubmit’,
      dataType : ‘html’,
      pathpart : this.value,
      nextNonce : PT_Ajax.nextNonce
      },
      function( response ) {
      $(‘div#empty-uploads-container’).append(response);
      }
      );
      return false;
      });
      });
      })(jQuery);

      1. There’s a short answer, and a long answer.

        The short answer: You don’t need to send the $_POST variable back as-is. You can send
        $build = '<div>' . $_POST['pathpart'] . '</div>';
        $response = json_encode($build);

        One caveat: DO NOT SEND $_POST VARIABLES BACK WITHOUT SANITIZING IT FIRST. Also check out wp_kses.

        The long answer: One of the real benefits of using AJAX is that you can reduce the amount of server processing by only sending what you need, then have the browser handle the data. The best way to do this is with a template system like handlebars.js.

        But as I tell my team. Get it working, then make it work better. Add templates to your todo list of things to learn, then check out a JS framework to boot.

        Good luck!

    9. Very helpful. Most other tutorials for this sort of thing are not as clean, concise and helpful for a beginner like me.

      I am using your tutorial as a starting point for making a jquery autocomplete in wordpress. Since I was struggling with this, I placed out a call for help on the wordpress.org forums, and I referenced your tutorial. ( http://wordpress.org/support/topic/jquery-autocomplete-front-end-with-wpdb?replies=1 ). Anybody who comes across this comment, please feel welcome to provide helpful feedback as I work towards adapting this tutorial into autocomplete.

      Cheers

    10. Jack, I honestly can’t thank you enough. I have been going nuts the last few (several) days, racking my brain trying to get super basic AJAX functionality working, in attempts to bump up my WordPress game. Every last tutorial out there is either 1) extremely heady and built for use by nerdy developer-developers to write actual WP plugins, or 2) is full of pre-knowledge assumptions with poor or impossible-to-follow writing. Again, thank you so much!

    11. Actually, I do have a question, as I am currently stumped! Ack! If you enter a number into the field (i.e.: and ID) how would you use that as a variable in a wordpress function? For instance: the_title(); ?

      – – –

      In my “page-ajax_input.php” file I put:

      Initial Placeholder Text

      – – –

      Then in “inputtitle_submit.js” I added the extra line in the function below to do the swap out:

      function( response ) {
      console.log( response );
      alert(response);
      document.getElementById(“replacement_location”).innerHTML = response;
      }

      … for the life of me I can’t figure out how to get a numerical ID to work with a WP function. I tried using the “build” method used in previous posts, but with no success. Sorry if I am missing an extremely obvious answer. Thanks! :)

      1. In the example above, in inputtitle_submit_inc.php instead of line 23 is where you would process data server side. Don’t forget to sanitize!

        Then return whatever data you’d like to use in inputtitle_submit.js instead of line 17.

    12. Thanks for your response. I totally see, thanks. I guess what I’m really saying is that there’s a disconnect between wordpress’s function library and inputtitle_submit_inc.php. I’m able to generate stand-alone php and HTML in input title_submit_inc.php, and pass that back to the page to render just fine. The problem is that when I attempt to call wordpress functions within inputtitle_submit_inc.php, such as “the_title();” or “the_date();” or whatever, nothing happens because the library isn’t isn’t found. Everything else that’s NOT wordpress function-dependent works just fine.

      Oh the joys of web design and development… *sigh*

      1. Ahh! That’s because those functions only work inside the loop. You need to use get_post($id) and then extract the data from the result to send back.

    13. I appreciate the tut!

      I have a related question though. I have built a similar ajax interaction but mine is more than a next button. I am using ajax to return custom post_type entries filtered by a form that sends the $_POST variables to my PHP function to populate the page. I am stuck on pagination of the ajax returned content. If I use the wordpress next_posts_link in my PHP function it returns the link as wp-admin/admin-ajax/page/2 etc. I am totally stumped?

    Leave a Reply