Handling Ajax Requests within WORDPRESS

Provide access to global URL admin-ajax.php and export this function to our WP POST

  • Use wp_enqueue_script to make JavaScript file my-ajax2.js accessible in our WP Post
  • Use wp_localize_script() to make URL admin-ajax.php useable in our scripts
  • Even though the admin-ajax.php resides in the admin area of your site, you can use it to
    process interactions from the front-end, as well as the back-end
  • In WordPress all Ajax requests are sent to admin-ajax.php for processing.
  • Modified functions.php :
  function my_js_scripts() 
        /* AJAX  request with wp_localize_script */
        wp_enqueue_script( 'hhu-script', get_stylesheet_directory_uri().'/scripts/my-ajax2.js', array( 'jquery' ),'0.9', false );
        wp_localize_script('hhu-script', 'hhu_vars', array('ajaxurl'   => admin_url( 'admin-ajax.php' ))    
   add_action( 'wp_enqueue_scripts', 'my_js_scripts' );


Define the AJAX Callback Function

  • To fire on the front-end for both visitors and logged-in users use wp_ajax_nopriv_ and wp_ajax_ action
  • Define a Callback Function named myAjax2() [ Called from our PHP code ]
  • Modified functions.php :
  function myAjax2()
       //get data from the ajax() call -  ID greeting3 is used 
     $greeting = $_POST['greeting3']; 
     $res1 = "<p>".$greeting;
     $res2 ='<br />  - get_template_directory()    : '.get_template_directory();
     $res3 ='<br />  - get_template_directory_uri(): '.get_template_directory_uri();
     $res4 ='<br />  - get_stylesheet_directory(): '.get_stylesheet_directory();
     $res5 ='<br />  - get_stylesheet_directory_uri(): '.get_stylesheet_directory_uri();

     $results = $res1.$res2.$res3.$res4.$res5.'</p>';  //Return String 

        // create new Ajax call for WordPress for users logged in and Not logged in  
 add_action( 'wp_ajax_nopriv_myAjax2', 'myAjax2' ); 
 add_action( 'wp_ajax_myAjax2', 'myAjax2' );

The HTML Code

  • ajax3-button button triggers the AJAX request
  • Hidden Input field greeting3 message will be send via AJAX request and its value is read by through $_POST[‘greeting3’] in function myAjax2()
  • HTML ID divp4 is used to display the results of our AJAX request
 HTML Code:
   <div class="p2" id="divp2"><b>OPS PANEL: </b> 
      <button id="ajax3-button" ">WP AJAX3</button>
   <input type="hidden" name="greeting3" id="greeting3" value="WP Details via AJAX request 3:" /> 
   <div class="p4" id="divp4"><p> Info PANEL - P4 - don't forget to scroll down for last message</p> </div>


JavaScript Code: my-ajax2.js triggering the AJAX reqest via JQuery

  • Defines the JavaScript file to be run via action parameter : myAjax2
  • Assigns to JS script parameter greeting the value from HTML ID : greeting3
  • The JavaScript object hhu_vars points to admin-ajax.php [ defined via wp_localize_script in Step 1]
  • Updates the HTML div divp4 with the AJAX call results
  • The action parameter is responsible for making the connection between the JavaScript file and the PHP code.
  • JavaScript Code: my-ajax2.js:
      var greeting = jQuery("#greeting3").val();    
          console.log('ajax3-button pressed') ;          
           type: 'POST', 
           url :  hhu_vars.ajaxurl,
           data: { action: 'myAjax2', greeting3: greeting  },
           success: function(data, textStatus, XMLHttpRequest)
                      console.log("Returing form AJAX request - Adding greetings to Div:  #divp4 ");  
            error: function(XMLHttpRequest, textStatus, errorThrown)
                    { alert(errorThrown); }
      console.log('Leaving ajax3-button Ajax action');


Leave a Reply

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