How to do Ajax in WordPress

updated 10th Jan 2018

Write a javascript function to trigger the ajax call

    jQuery('#button_or_something').on("click", function() {
            
     
        jQuery.ajax({
            url: ajax_object.ajax_url,
            data: {
                action: 'like_or_not',  /* this is appended to add_action on server side */
                id: '99'
            },
            type: 'GET',
            success:function(response){
                //alert('back from ajaxe '+response);
                
                /* if you want to update something based on the response text */                        
                jQuery('#gb_div_to_update').html(response);        
            
                       

            }




        });
            
		
    });

Put js above in my_js_file.js (see later in this post).

Wrap in code below for nice loading:

jQuery( document ).ready(function() {    put above code here     });

To see how to send a form via ajax see here.

 

Write a php function to handle the ajax call (you could put this in functions.php)

add_action('wp_ajax_nopriv_like_or_not', 'green_like_or_unlike');   
add_action('wp_ajax_like_or_not', 'green_like_or_unlike'); /* notice like_or_unlike appended to action name of wp_ajax_ */


function green_like_or_unlike() {

    
   echo "hitting the php function ok";
   die(); // gets rid of the 0 at the end of ajax response
    
    
}

 

There is one final piece, you might notice the ajax_object.ajax_url in the Javascript function above. We need to make this available in the js file that this function is in. This needs to be done in php.

wp_localize_script( 'green-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );

Include ajax_url like this (below)

function theme_enqueue_styles() {

    /*
     * include the js
     */

    wp_enqueue_script('green-script', get_stylesheet_directory_uri() . '/my_js_file.js', array('jquery'));

        
    // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
	wp_localize_script( 'green-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
    
    
}

add_action('wp_enqueue_scripts', 'theme_enqueue_styles');

 

Leave a Comment