Byronyasgur's Blog

Random Web Developer Stuff, Mostly WordPress

Frontend ( Forward Facing ) Ajax in WordPress

on June 27, 2011

Note: I have had some problems getting the code to render properly in the code snippits, so please double check after you copy for minor errors eg spurious “& nbsp;” etc.
I spent such a long time figuring this out that I figured I had to share it, even though I’m no Ajax expert. WordPress requires a bit of knowledge to get forward facing AJAX working on so this is an example coding of a basic “Hello World” plugin. It does very little on it’s own but the code could be used to build something more useful, and of course it could be a theme function instead. Note this code is largely unnecessary to do AJAX in the admin section.

I haven’t really explained the code in detail but I have commented it a bit and also if you look carefully at the titles of the functions, variables handles etc (in conjunction with the wordpress codex ) you can get a fair idea of what’s going on eventually. To be brutally honest it’s not exactly the most understandable thing in the first place so you might need to spend a while looking at it … do note that the most important link in the chain is the “action” …. and that this necessarily (because i want to serialise the form) must be passed to the javascript via a hidden field. See end of the article for instructions on doing this without a form, but you still need to pass the action somehow.

Note also that all Ajax in wordpress ( even the front end stuff ) gets processed via admin-ajax.php which is part of WP. This is probably the hardest thing to get used to especially if you’ve done Ajax outside of WordPress. This is how WordPress does it. Also I’m sorry I cant be more explanatory about the localize_script function which in a way is the bit that ties it all together, and to be honest I don’t fully understand this part yet myself. Furthermore at the time of writing there is very little data available on this function, but it’s actually to do with localization but somehow it’s necessary to use it here to tie your Ajax file to admin-ajax.php. Please feel free to add info in the comments if you have anything to make this more clear.

This plugin is not secure as it stands and nonces would need to be added, also it is not very efficient as it puts the JS on every page.

Worth noting also that there are 2 methods of getting the AJAX on your page – one is the way i describe in this article( using localise_script ) … the other is to put the ajax in the head ( using an init or some other add action ), as described by Donncha O Caoimh on this page

I am using jquery to do the AJAX – ( dont use $ in WP – use ‘jQuery’)

The chain of events goes roughly like this:

  • shortcode draws form and response area …. submitting the form triggers the javascript which has been placed on the page using enqueue and localise scripts
  • the jquery ajax function “post” gets the form data and processes it by sending it to the_ajax_script.ajaxurl ( localise script has set this to be admin-ajax.php )
  • admin-ajax.php is now aware of the “action” “the_ajax_hook'” because it has been sent along with the form ( hidden field)
  • wordpress now processes whichever function( the_action_function ) is tied to the action (the_ajax_hook) in the 2 wp_ajax_ tags
  • the_action_function can contain anything at all – most notably it can query the database and return a result
  • the results of the_action_function are passed back to the response function within the jquery “post” function with will operate on them ( critically without refreshing )

Below is the code for the plugin. Create a new folder in your plugins folder. You can copy the php into a file in your plugins folder, call it helloworld.php for instance; create another file for the javascript – it needs to be called ajax.js and be in the same folder … then activate the “Hello World Ajax Frontend 2″ plugin the plugins section of WP. It uses a shortcode to display so create a new page and type [hw_ajax_frontend] into the visual editor and then view that page. You should see a small form and a response area – the operation is fairly self explanatory.

By the way … wp_localize_script() which is used in this code is explained quite well here.

<?php
 /*
 Plugin Name: Hello World Ajax Frontend 2
 Plugin URI: http://rainrain.com
 Description: A simplified ajax front end
 Version: 2
 Author: Bob Murphy
 Author URI: http://rainrain.com
 */

// enqueue and localise scripts
 wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) );
 wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
 // THE AJAX ADD ACTIONS
 add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' );
 add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); // need this to serve non logged in users
 // THE FUNCTION
 function the_action_function(){
 /* this area is very simple but being serverside it affords the possibility of retreiving data from the server and passing it back to the javascript function */
 $name = $_POST['name'];
 echo"Hello World, " . $name;// this is passed back to the javascript function
 die();// wordpress may print out a spurious zero without this - can be particularly bad if using json
 }
 // ADD EG A FORM TO THE PAGE
 function hello_world_ajax_frontend(){
 $the_form = '
 <form id="theForm">
 <input id="name" name="name" value = "name" type="text" />
 <input name="action" type="hidden" value="the_ajax_hook" />&nbsp; <!-- this puts the action the_ajax_hook into the serialized form -->
 <input id="submit_button" value = "Click This" type="button" onClick="submit_me();" />
 </form>
 <div id="response_area">
 This is where we\'ll get the response
 </div>';
 return $the_form;
 }
 add_shortcode("hw_ajax_frontend", "hello_world_ajax_frontend");
 ?>

this is the javascript file ….. ( needs to be called ajax.js )

 function submit_me(){
 jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize()
 ,
 function(response_from_the_action_function){
 jQuery("#response_area").html(response_from_the_action_function);
 }
 );
 }

Not using a form

If you want to trigger your javascript (eg on the page load) as opposed to via a form then you will need to get the “action” hook into the jQuery.post function some other way other than via the form ….. it’s actually easier to do it this way because all you need to do is add action:whatever_your_action is to the jQuery.post…. like this

Put in:

{ 'action': 'the_ajax_hook' }

as the second argument of the jQuery.post function instead of

jQuery("#theForm").serialize()  // which had simply serialised the form (INCLUDING the "action" in the hidden field)

like this:

jQuery.post(the_ajax_script.ajaxurl, { 'action': 'the_ajax_hook' } ,
 function(response_from_the_action_function){
 jQuery("#response_area").html(response_from_the_action_function);
 }
 );
 

Data. Using this method means there is no data going forward as there would be using serialize form where all the form data would have been passed along with the action in the serialized form …. but you can send data this way

{
action: 'the_ajax_hook',
data:'string',
value:5,
function_output:jQuery('#element').val(),
etc,
etc
}

more examples at the bottom of this page

N.B. WordPress needs ‘action': ‘whatever_your_hook_is’  to work using this method whether it comes in directly or via form hidden input and serialize form

RELATED LINKS

a couple of other places you might want to reference

http://codex.wordpress.org/AJAX_in_Plugins ( and the links at the bottom of that page )

http://wordpress.tv/2011/05/06/will-anderson-using-ajax-in-plugins-and-themes/ ( slightly tedious but he does pretty much cover everything – grab a notepad first though )

<?php
/*
Plugin Name: Hello World Ajax Frontend 2
Plugin URI: http://rainrain.com
Description: A simplified ajax front end
Version: 2
Author: Bob Murphy
Author URI: http://rainrain.com
*/

// enqueue and localise scripts
wp_enqueue_script( ‘my-ajax-handle’, plugin_dir_url( __FILE__ ) . ‘ajax.js’, array( ‘jquery’ ) );
wp_localize_script( ‘my-ajax-handle’, ‘the_ajax_script’, array( ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ) ) );
// THE AJAX ADD ACTIONS
add_action( ‘wp_ajax_the_ajax_hook’, ‘the_action_function’ );
add_action( ‘wp_ajax_nopriv_the_ajax_hook’, ‘the_action_function’ ); // need this to serve non logged in users
// THE FUNCTION
function the_action_function(){
/* this area is very simple but being serverside it affords the possibility of retreiving data from the server and passing it back to the javascript function */
$name = $_POST['name'];
echo”Hello World, ” . $name;// this is passed back to the javascript function
die();// wordpress may print out a spurious zero without this – can be particularly bad if using json
}
// ADD EG A FORM TO THE PAGE
function hello_world_ajax_frontend(){
$the_form = ‘
<form id=”theForm”>
<input id=”name” name=”name” value = “name” type=”text” />
<input name=”action” type=”hidden” value=”the_ajax_hook” />&nbsp; <!– this puts the action the_ajax_hook into the serialized form –>
<input id=”submit_button” value = “Click This” type=”button” onClick=”submit_me();” />
</form>
<div id=”response_area”>
This is where we\’ll get the response
</div>';
return $the_form;
}
add_shortcode(“hw_ajax_frontend”, “hello_world_ajax_frontend”);
?>

About these ads

35 responses to “Frontend ( Forward Facing ) Ajax in WordPress

  1. Cole says:

    Finally! I have been trying to figure this out forever. This script works perfectly and is very easily expanded.

    I only wish you had explained the two lines following “// get name from input” in the js file as well as that hidden “the_ajax_hook” thing. I set my script to start when the page loads rather than when the submit button is pressed, but since I don’t understand that part of the code, I had to leave that hidden field in there.

    Very helpful, though. Thanks!

    • byronyasgur says:

      Glad you found it helpful – yes its easy when you know how but nigh impossible otherwise …. you raised a good point … i have updated the post …… have a look at the new bottom section and see if it answers your question ( i haven’t tested the code just copied and pasted it out of previous experiments … nearly sure it’s all 100% but if you spot an error please let me know, thanks)

      edit: forgot about the // get name from form input question …. i cant really change it now ( dont have time to test it this minute ) but that line looks suspiciously like it’s unnecessary to me

      var thename = jQuery(“input#name”).val();

      all it’s doing is getting the value which had been typed into the name field of the form and assigning it to var thename ….. but i am using serialise form so all this i should be done automatically – one would use this if you werent serialising the form like this {‘action':’the_hook’, ‘name':thename} …. sorry i cant be more clear but i’m relatively new to this so i dont want to just mess with the code until i’ve tested it which i will do at some stage in the future

  2. Cole says:

    Excellent! That worked perfectly. I appreciate the help!

  3. seyha says:

    I would like to convert my code as below to Ajax plugin Please guide me thanks in advance.

    jQuery(document).ready(function() {
    jQuery(“#user_login”).blur(function() { // when focus out
    jQuery(“#message”).html(“checking username…”); //before AJAX response
    var form_data = {
    action: “check_username”,
    username: jQuery(this).val()
    };
    jQuery.ajax({
    type: “POST”,
    url: “/wp-content/plugins/sidebar-login/functions.php”,
    data: form_data,
    success: function(result) {
    jQuery(“#message”).html(result);
    }
    });

    });
    });

  4. byronyasgur says:

    You would need to do the following:

    • put the code into a js file
    • make a plugin file in your plugins folder containing a similar comment section as above …. Plugin Name: Your plugin name….. etc)
    • in that file enqueue and localise your js
    • you can also put on this page the pre ajax content eg a form was used above
    • you also should probably put the contents of /wp-content/plugins/sidebar-login/functions.php on this page as a function ( or else include it or whatever ) … you will need to link this function to the ajax using action: and the add action handles as explained below

    In your js …. as regards the jQuery.ajax function i have never used this so I dont know how to use it but you should be able to figure out how to either use the jQuery.post or jQuery.get or else adapt your jQuery.ajax if you actually need to use that …..
    in either case the URL will have to be admin-ajax.php to get it working in wordpress as explained above
    then you will send the handle to your php function by sending { ‘action’: ‘the_ajax_hook’ } as the second parameter of jQuery.post or jQuery.get where the_ajax_hook is the handle to the function referenced in add_action( ‘wp_ajax_ and add_action( ‘wp_ajax_nopriv_

    … i think the line url: “/wp-content/plugins/sidebar-login/functions.php”, will never work …. as i was saying above this is the key to frontend ajax in WP … you ALWAYS pass admin-ajax.php in as the url and then you send in along with that a handle to a function ( so put the contents of functions.php into a function and reference that using the 2 add actions and then send the handle you gave it in the add actions like this { ‘action’: ‘the_ajax_hook’ } in the ajax ( or you could serialize the data instead as i did in the first part of the section )

    hope this helps

  5. How does this work where a jquery UI routine (e.g. autocomplete) already handles AJAX calls internally?

    Can we just by pass the WordPress mechanism and use the jquery UI built in handling, or do we need to rework the jquery UI routine to use WP AJAX mechanism?

    • byronyasgur says:

      love to be able to help, i can see your predicament but i’m not in a position to look into it at the moment, sorry. I have a feeling that it’s possibly not well documented at this stage. If you cant work it out yourself and don’t get another reply here then I think if you ask the question on wp stack exchange,http://wordpress.stackexchange.com/ ( maybe referring to this post and that you need to further build on it) then maybe someone might be able to help you.

  6. Have a look at this comment (the entire post is well worth reading) http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#comment-112

    It states that WP 3.0 has a new wp-ajax.php file in the root folder.

  7. John Nicholson says:

    great launchpad for me – after hideous complexity everywhere else this worked (and working) example got me going. Thanks a lot.

  8. William says:

    This code works great, but I’m using it to load a large form, and when the user clicks submit it looks like nothing is happening right away because there is no “Working…” indicator. How would I go about adding some kind of busy icon so that the user knows that the script is working right away? I’ve searched everywhere for documentation that could help me with this to no avail.

    • byronyasgur says:

      Sorry I only do ajax occasionally so i’m no expert at all, i just posted my findings here as i did this job …….unless someone else here can help, but i seem to remember that the jquery site had some kind of working indicator, or it might have been jquery UI either. Hope you find it.

    • Cole says:

      I use JavaScript to swap the submit button for an animated loading gif when the form is submitted. Then, I tell the loading gif to go away and the submit button to return when the Ajax is done. I do this by putting a div with an ID around the submit button and then using innerHTML to swap what’s inside the div. Works well because it ensures you can’t submit again until the first submittion is processed.

  9. As a heads up, your font copy/pastes as nonstandard characters, simple find-and-replace on ” vs. “ and ‘ vs ’ clears up a “Parse error: syntax error, unexpected T_STRING” error message when activating plugin.

    • byronyasgur says:

      Thanks, yes you were right. I had the code contained in blockquotes because wordpress.com doesnt like code tags, and they seemingly changed the quote marks. I have changed things around now in a few different ways so hopefully it still works right.

  10. Alex Gold says:

    Hey, this works wonders! Thanks for bringing it up. I’m having som issues though, because I’m trying to use multiple instances this script (for different pages/processes). The first one works perfectly, but the second just returns the new text as “-1″ and nothing else. I’m assuming it’s clash of function names and whatnot, and I’ve tried to change the ones I could see, but to no avail. I stripped out the unnecessary code, and the problem occurs with this setup (the ajax file remains as default):

    admin_url( ‘admin-ajax.php’ ) ) );
    // THE AJAX ADD ACTIONS
    add_action( ‘wp_ajax_the_ajax_hook’, ‘vocabulary_show_by_function’ );
    add_action( ‘wp_ajax_nopriv_the_ajax_hook’, ‘vocabulary_show_by_function’ ); // need this to serve non logged in users

    // Permanent text
    function print_this()
    {
    echo ”
    “;

    // Initial text
    echo ”;

    echo ”;
    echo “”;
    }

    // New text
    function vocabulary_show_by_function()
    {
    echo “hi!”;
    die();
    }
    // ****************************************************************

    add_shortcode(“vocabulary_by_function”, “print_this”);
    ?>

    Any idea what I can do? Thanks so much!
    – Alex

  11. Alex Gold says:

    (Side note, I just noticed I was missing “method=’post'” and the ” from this example, but adding those didn’t fix it :).

  12. Alex Gold says:

    Hmmmm . . . Actually, it looks like it stripped the PHP stuff from my post. I just put it in a txt file and uploaded it for you though, so you can see it at http://mygreekstudies.com/code.txt

    Thanks again :).

    • byronyasgur says:

      Alex, By multiple instances do you mean the one plugin dealing with more than one form/button etc, or do you mean more than one plugin ? – ps i think you have to put code in [ sourcecode language="php" ] php here [ /sourcecode ] ( without the spaces after/before the square brackets ) ( same for javascript )

      eg

      <?php 
      echo "test";
      ?>
      
    • byronyasgur says:

      I copied your code and tried it and it did actually return the minus 1 for me but only because the form name had changed so I had to put that into the jquery in place of the original form name …. so just in case that’s it.

  13. Steve Padgett says:

    Using the example, Hello World Ajax Frontend 2, I was able to successfully perform an Ajax request / response. However, I need to NOT use a form but was unable to implement the suggestions provided.

    Could you provide an example where there is no form and one parameter is passed, specifically code for ajax.js and the code for the hello_world_ajax_frontend function .

    much appreciated !

  14. random user/hacker says:

    There is a bug in the shortcode function hello_world_ajax_frontend(), it should not: echo “<form…", correct is: return "<form…"

  15. byronyasgur says:

    Yes I think you’re right … I removed it.

  16. Jay says:

    Awesome , thank you!

  17. Ashish says:

    Thanks. The technique it helped me.

  18. I think it s important to be aware that in order to make ajax work on something like a page template (like a custom login form or a user-submitted image form as part of your child theme) you must include the server side wp-ajax handler inside your child theme’s functions.php file. not in the page template itself.

    You can not just code the “add_action(wp-ajax…” stuff in a page template file without (I think) doing something very extraordinary and unwise like including big chunks of wordpress core in that template. I hope this helps someone avoid a day of frustration, wondering why their server side code always returns a “0” with no errors (since the JS part can find the wp-ajax.php code but that server code is not really “alive” outside of wp).

    Good luck and have fun!

  19. […] following this tutorial to use front-end ajax to submit an email from a form and include information such as the current […]

  20. Jay says:

    Excellent post. Still trying to “wrap” my head around it though. Just one question…

    What is meant by “forward facing” or “front end” ajax? Can’t seem to find any info on this vernacular.

    • byronyasgur says:

      Forward facing in WordPress terms means something that the public sees as opposed to what you the admin sees when you log in to wp-admin. Admin ajax is relatively straightforward in WP. Forward facing is not a simple.

  21. subas says:

    Thanks for this great article..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: