Simple Ajax Example

Posted

This is a basic example of how to use AJAX in WordPress. 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: ajaxurl,
		data: {
			'action':'example_ajax_request',
			'fruit' : fruit
		},
		success:function(data) {
			// This outputs the result of the ajax request
		  	console.log(data);
		},
		error: function(errorThrown){
		    console.log(errorThrown);
		}
	});
});

PHP Piece

function example_ajax_request() {
	// 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);
	}
	// Always die in functions echoing ajax content
   die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
// add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

17 thoughts on “Simple Ajax Example

  1. Teerath Kumar wrote:

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

  2. Luis wrote:

    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?

    • Devin wrote:

      Correct.

  3. Nikolay wrote:

    Not working, it says:

    ReferenceError: ajaxurl is not defined

    • Siva wrote:

      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' ) ) );

      • Paul wrote:

        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

  4. Matthew wrote:

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

    • Devin wrote:

      Yes.

  5. Denish wrote:

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

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

    • Devin wrote:

      No, you’ll need to call a function.

  6. Henry wrote:

    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' );

    • Devin wrote:

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

      • Henry wrote:

        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. Harun wrote:

    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.

    • Devin wrote:

      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. tarun wrote:

    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

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