How to call ajax in wordpress

Actually, WordPress comes with a handy function to access admin-ajax.

Requirements

  • In wp-admin you do not need to do anything, the js library is always loaded
  • In the front-end you need to enqueue the script wp-util, like this:

    add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
    
    function my_enqueue_function() { 
        // Option 1: Manually enqueue the wp-util library.
        wp_enqueue_script( 'wp-util' );
    
        // Option 2: Make wp-util a dependency of your script (usually better).
        wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
    }
    

The JS Library

The wp-util script contains the wp.ajax object that you can use to make ajax requests:

 wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )

Your example:

wp.ajax.post( "get_data", {} )
  .done(function(response) {
    alert("Your vote could not be added");
    alert(response);
  });

PHP code

Of course, you still need to create the wp_ajax_* hooks in your PHP script.

add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );

function my_ajax_handler() {
    wp_send_json_success( 'It works' );
}

Tip:

For Ajax responses WordPress provides two functions:

wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (i.e., they exit;)


In backend there is global ajaxurl variable defined by WordPress itself.

This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.

Good way to do this is to use wp_localize_script.

Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }
 add_action( 'wp_enqueue_scripts', 'my_enqueue' );

After localizing your JS file, you can use my_ajax_object object in your JS file:

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: my_ajax_object.ajax_url,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});