Blog

A very simple Ajax example

A lot of WordPress Ajax examples seem to be overly complex and confusing. I’ve created a short little script that demonstrates the basics of how to an Ajax request. To use it, just do the following:

  1. Copy the code into your plugin or theme
  2. Search and Replace “MY_ACTION” with your own unique action name.
  3. Move the HTML and Javascript bit where you want it.
  4. If you are planning to use this on the front end you will need to initialise the ajaxurl variable and allow the wp_ajax_nopriv_* actions.  These are provided in the code, just uncomment where it says “Uncomment next line”.
  5. Then the fun part: Set up your javascript to pass any data to the ajax call, and your custom wp_ajax_MY_ACTION function to handle the data and do something.
/**
 * Display a custom menu page
 */
function demo_ajax_plugin_page(){
  
  $ajax_nonce = wp_create_nonce( "MY_ACTION_nonce" );
    ?>
          <script type="text/javascript">
        
        function run_ajax_demo() {
          
          var data = {
            'action': 'MY_ACTION',
            'security': '<?php echo $ajax_nonce; ?>', /* secure your ajax script */
            'an_optional_argument': '1',
            'text_box_contents':jQuery("#a_text_box").val()
          };

          /* Uncomment next line to use on front end */
          // ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; /* Uncomment this to use on front end */
          // ajaxurl is defined within admin. If using it within admin, add this line of code:
          
          
          jQuery.post(ajaxurl, data, function(response) {
            jQuery("#ajax_output").html("Here is the reponse from your ajax script: "+response);
          });
          
        }
        </script>
        
        <br/><br/>
        
        A text box for demo purposes: <input id='a_text_box'/>
        
        <br/><br/>
        
        <button type='button' onclick='run_ajax_demo()'>Click this button to run your ajax script.</button>
        <div id='ajax_output'>
          This is empty.
        </div>
        <?php 
}

/*
 * Register your custom ajax handler here
 */
add_action( 'wp_ajax_MY_ACTION', 'wp_ajax_MY_ACTION' );

 /* Uncomment next line to use on front end */
 //add_action( 'wp_ajax_nopriv_MY_ACTION', 'wp_ajax_MY_ACTION' );

function wp_ajax_MY_ACTION() {
  check_ajax_referer( 'MY_ACTION_nonce', 'security' );
  
  var_dump($_REQUEST);
	wp_die(); // this is required to terminate immediately and return a proper response
}

0 comments on “A very simple Ajax exampleAdd yours →

Leave a Reply

Your email address will not be published.