How to call ajax url properly on wordpress?

by jasen_gottlieb , in category: PHP CMS , a year ago

How to call ajax url properly on wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@jasen_gottlieb 

To properly call an AJAX URL in WordPress, follow these steps:

  1. Register your AJAX action in the theme's functions.php file or in a custom plugin. Use the wp_ajax_{action} for logged-in users and wp_ajax_nopriv_{action} for non-logged-in users. Here's an example:
1
2
3
4
5
6
7
8
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_function' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_function' );

function my_ajax_function() {
    // Handle AJAX request
    wp_send_json_success( 'Success!' );
    wp_die();
}


  1. Enqueue the AJAX script in your theme's functions.php file or in a custom plugin. This makes sure WordPress is aware of the AJAX request. For example:
1
2
3
4
5
function enqueue_ajax_scripts() {
    wp_enqueue_script( 'my_script', get_stylesheet_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'my_script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_scripts' );


  1. Create a JavaScript file, my_script.js, in your theme or plugin folder. Here's an example of how to make an AJAX call:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
jQuery(document).ready(function($) {
    $('#my-button').click(function(e) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: {
                action: 'my_ajax_action'
            },
            success: function(response) {
                console.log(response);
            },
            error: function(errorThrown) {
                console.log(errorThrown);
            }
        });
    });
});


  1. Lastly, create the element triggering the AJAX call in your theme or plugin template file. For example:
1
<a href="#" id="my-button">Send AJAX Request</a>


This setup ensures that when the button with ID my-button is clicked, it triggers the AJAX request to the registered AJAX action my_ajax_action, which then executes the callback function my_ajax_function.