Simple Ajax Example

This is a basic example of how to use AJAX in WordPress in the admin area. It shows how to take a variable from javascript, pass it to a PHP function (altering it slightly), and then pass it back to the javascript.

This assumes you already know how to enqueue javascript, etc.

Javascript Piece

jQuery(document).ready(function($) {
 
    // We'll pass this variable to the PHP function example_ajax_request
    var fruit = 'Banana';
     
    // This does the ajax request
    $.ajax({
        url: example_ajax_obj.ajaxurl,
        data: {
            'action': 'example_ajax_request',
            'fruit' : fruit,
            'nonce' : example_ajax_obj.nonce
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });  
              
});

PHP Piece

<?php
function example_ajax_request() {

    $nonce = $_POST['nonce'];

    if ( ! wp_verify_nonce( $nonce, 'example-nonce' ) ) {
        die( 'Nonce value cannot be verified.' );
    }

    // The $_REQUEST contains all the data sent via ajax
    if ( isset( $_REQUEST ) ) {

        $fruit = $_REQUEST['fruit'];

        // Let's take the data that was sent and do something with it
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }

        // Now we'll return it to the javascript function
        // Anything outputted will be returned in the response
        echo $fruit;

        // If you're debugging, it might be useful to see what was sent in the $_REQUEST
        // print_r( $_REQUEST );

    }

Using with a Theme

There’s two differences when using this with a theme or frontend.

PHP Update

In the PHP piece, you need to add also add this line:

 // Always die in functions echoing ajax content
die();

This allows visitors that aren’t logged in to run the ajax request.

Javascript Update

In the javascript piece on the frontend, you’ll likely see this error in the console:

wordpress ajaxurl is not defined

This is because WordPress does not define ajaxurl as a global variable on the frontend. Instead, we’ll need to define it ourselves. An easy way to do this if we’re already enqueuing our script is to use wp_localize_script to output the URL:

<?php
function example_ajax_enqueue() {

	// Enqueue javascript on the frontend.
	wp_enqueue_script(
		'example-ajax-script',
		get_template_directory_uri() . '/js/simple-ajax-example.js',
		array( 'jquery' )
	);

	// The wp_localize_script allows us to output the ajax_url path for our script to use.
	wp_localize_script(
		'example-ajax-script',
		'example_ajax_obj',
		array(
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'nonce' => wp_create_nonce( 'example-nonce' )
		)
	);

}
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' );

If you view the source on the frontend, you should now see a global variable defined on the frontend called “example_ajax_obj”. To get the original javascript working on the frontend, update the ajaxurl variable to use this new variable:

url: example_ajax_obj.ajaxurl
Comments

46 responses to “Simple Ajax Example”

  1. I am a software engineer,
    I appreciate your work done and such a social nature to help others.
    Thanks

    Teerath Kumar Avatar
    Teerath Kumar
  2. Hi Devin,
    Simple and effective, i have seen others ajax tutorials with wordpress (complex ones), but until now, i do really understand how it works, the only question i still have is this:
    In this hook:

    add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

    the hook name must start with “wp_ajax_xxxxxxx” because wp define it to be in that way, right?

  3. Not working, it says:

    ReferenceError: ajaxurl is not defined

    1. Since WP 2.8 version, ajaxurl works only for administration dashboard purpose.
      try to use
      wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

      1. Hi,

        This doesn’t seem to work for me. I added the wp_localize_script bit to my functions.php but still get the ajaxurl is not defined error. I’m using your tutorial on a wp frontend page.

        Thanks

      2. Paul, use ajax_object.ajaxurl, because “ajax_object” is the name that WordPress will give the javascript object which will contain all the supplied variables.

      3. @Jos Faber – Can you explain what you mean a little more? I’m having what seems like a similar issue.

  4. Hi, is this example still up to date for 2014? Thanks

  5. How can i call another php file without passing an variable ?

    Instead of function. Can i run another .php file?

    1. No, you’ll need to call a function.

  6. Is it possible to use the PHP function for logged-out users only? i.e. Can I omit the following?

    add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

    1. I believe so. But that means the action wouldn’t work for you if you were logged into the site and testing it.

      1. Thanks for your reply.

        That’ll be fine. My use case is a registration form so the end user will never be logged-in at the point at which this fires.

  7. Hi, I’m working on “Load More” button and I’m using $.get. Is it safe to use normal http://example.com/page/2 link because I’m only getting data.

    1. That works if you’re purely pulling from the front end. I’d also look at the “Load More” code in JetPack if you’re looking to pull entire posts (and want scripts, shortcodes, etc execute correctly).

  8. Thank you, it works perfectly :)

  9. Hi, great tutorial, simple and to the point. I see that the jquery code logs the data echoed by the php function. Is there anyway to use the variables defined in the php function inside the jquery success output?

    Thanks

  10. hey dude,

    Thanks. This helped me a lot. Was building a plugin and got response 0 all the time.

    I forgot to require_once() the actual php file that was used for processing.

  11. Devin, great simple tutorial but I would try to update the tutorial with using a nonce or either tell beginner AJAX developers that using nonce should be done for security reasons.

    Again Nice Simple Tutorial for Beginners.

    DL

  12. Hi if i want to print the $fruit value in php i am using print_r($fruit); but its not printing.can you please provide a solution on that.

  13. I solved the “ajaxurl is not defined” issue in this way:

    (1) Added this to my php:

    echo(‘\n’);

    (2) Added this to the top of my javascript:

    var ajaxurl = $(“input#ajaxurl”).val();

    Worked like a charm after that. Thanks Devin!

    Jerome Gaynor Avatar
    Jerome Gaynor
  14. Sorry, the comment removed my code… I’ll try again. The bit I added in step 1 is:
    <input type="hidden" id="ajaxurl" value="” />

    Jerome Gaynor Avatar
    Jerome Gaynor
  15. Well, that didn’t work either… tried to help…

    Jerome Gaynor Avatar
    Jerome Gaynor
    1. Yeah, sorry, code gets stripped out of comments. You can post a it in pastebin to share. But I would suggest the wp_localize_script method over something like that.

  16. Hello, I’m having a very strange issue.

    The AJAX is only working on one page. It won’t work with any other pages on the site. In the console, it says “Can’t find variable: ajaxurl”. I’m loading the JS globally as well. I could see that happened if I loaded it conditionally such as is_page() or something like that but its global. Am I missing something simple?

  17. Its giving me a “ReferenceError: Can’t find variable: ajaxurl”

  18. finnaly i understood how ajax in wp should work (after a whole day of searches) but is not working for me because the ajaxurl is not defined.

    tried the:

    wp_localize_script( ‘ajax-script’, ‘ajax_object’, array( ‘ajax_url’ => admin_url( ‘admin-ajax.php’ ) ) );

    also:

    wp_localize_script( ‘ajax-script’, ‘ajax_object.ajaxurl’, array( ‘ajax_url’ => admin_url( ‘admin-ajax.php’ ) ) );

    but still it can’t recognize the ajaxurl…

    i’m new to wp so i would be glad if u can update the post with how to register the ajaxurl variable.

    also i can see that im not the only one having this question.

    thanks

  19. @Cezar @Garret

    Make sure in your js you are calling the function name of your script

    Example if the following

    wp_localize_script( ‘ajax-script’, ‘ajax_object’, array( ‘ajaxurl’ => admin_url(‘admin-ajax.php’ ) ) );

    Then your js url would be ajax_object.ajaxurl

  20. php piece is included in funtions.php, and where javascript piece should be included?

  21. For ajaxurl error just try changing to ‘ ‘

  22. simple and Perfect just thanks.

    I3ehrang Avatar
  23. +1 Simple and Perfect just thanks!

  24. I don’t understand – where do I have to put my PHP piece?

    1. In your theme’s functions.php file. If you are using child theme then in it’s function file.

  25. this example is awesome thanks for it

  26. I have spent a full day on this. All I get returning to the script is the html of the page itself. It does’t make any sense. I don’t know if using the Genesis framework is causing issues.

  27. change ajaxurl to ajax_url if you are having a problem with “ReferenceError: Can’t find variable: ajaxurl”

  28. Thank you very much but i tried the example on my wordpress website and i still getting nothing, only empty response, it seems the function isn’t executing, how can i call the url to activate the ajax function inside php page? can you give me an example?
    I readed the other comments but nothing to do
    Thank you in advance.

    1. Hi Leonardo. I can see how this tutorial may have been confusing if you were trying to use it on the frontend. I’ve updated the post with additional snippets that explain in more detail how to use it with a theme.

  29. Is there a typo :
    the frontend called “example_ajax_onj”

    1. Thanks, fixed.

  30. Thanks for this simple example. Does this still work in April 2018? Also what folder should the php file go into?

    1. Should still work in 2018. If this is going in a theme, you could put it in functions.php, or any file include from functions.php.

  31. I have a question: I want to use an external custom.php file (located inside my child theme) for receiving the ajax request and processing and not using a simple function insite WP’s functions.php file. Is that possible?

Leave a Reply

Your email address will not be published. Required fields are marked *