Simple Working Example

In your php (html) page
  $AjaxUrlHtml = "var ajaxurl = '" . admin_url('admin-ajax.php') . "';";
  $AjaxNonce = wp_create_nonce( 'my-nonce-special-string' );
  
  $HtmlOutput .= <<<_END
  
  <div onclick="DoAjaxPost();" ></div>
  
  <script type="text/javascript" >
    $AjaxUrlHtml

    function DoAjaxPost() {
        var post_data = {
                   'action': 'my_ajax_action_callback',   //The name of the ajax callback action in functions.php
                   'security': '$AjaxNonce',
                   'my_value_1': 9876
        };

        jQuery.post(ajaxurl, post_data);
    }
  </script>

_END;
In functions.php
add_action ( 'wp_ajax_my_ajax_action_callback', 'my_ajax_action_callback' );        //For AJAX calls made for logged in users
add_action ( 'wp_ajax_nopriv_my_ajax_action_callback', 'my_ajax_action_callback' ); //For AJAX calls made from non logged in users
function my_ajax_action_callback()
{
  //Check the nonce
  check_ajax_referer('my-nonce-special-string', 'security');      //Nonces are tied to the user ID which is handled by php.  THis will die(); if the nonce check fails
  
  //$user_id = get_current_user_id();                             //Use this if your function wants the wordpress user_id (secure method, don't pass it as an ajax argument)

  if ($my_value_1 == 9876)
  {
    
    //Do something
    
  }
  
    wp_die();     //Terminate immediately and return a proper response
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published.