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

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.


    24 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!

    Leave a Reply