Setting Up AJAX in WordPress:

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() { // AJAX function implementation }

Enqueuing AJAX Script:

function enqueue_ajax_script() { wp_enqueue_script('ajax-script', get_template_directory_uri() . '/js/ajax-script.js', array('jquery'), '1.0', true); wp_localize_script('ajax-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'))); } add_action('wp_enqueue_scripts', 'enqueue_ajax_script');

Sending AJAX Request from JavaScript:

jQuery.post(ajax_object.ajax_url, { action: 'my_ajax_action', data: 'my_data' }, function(response) {
    // Handle AJAX response
});

Creating a Frontend AJAX Request:

jQuery.ajax({ type: 'POST', url: ajax_object.ajax_url, data: { action: 'my_ajax_action', data: 'my_data' }, success: function(response) { // Handle AJAX response } });

Processing AJAX Request on Server:

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() { // AJAX function implementation }

AJAX Form Submission:

jQuery('#my-form').submit(function(e) {
    e.preventDefault();
    jQuery.ajax({
        type: 'POST',
        url: ajax_object.ajax_url,
        data: jQuery(this).serialize(),
        success: function(response) {
            // Handle AJAX response
        }
    });
});

Similar Posts