wp ajax error handling
Step 1: Enqueue jQuery Library Add the following code to your theme's functions.php file or a custom plugin to enqueue the jQuery library.
function enqueue_custom_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
Step 2: Localize Script Localize the script to make the AJAX URL available for the JavaScript file.
function localize_script() {
wp_localize_script('your-script-handle', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'localize_script');
Step 3: Create AJAX Action Add the following code to your theme's functions.php file or a custom plugin to handle the AJAX request.
function custom_ajax_function() {
// Your AJAX logic here
// Send a JSON response
wp_send_json_success($data);
wp_die();
}
add_action('wp_ajax_custom_action', 'custom_ajax_function');
add_action('wp_ajax_nopriv_custom_action', 'custom_ajax_function');
Step 4: Handle AJAX Request in JavaScript In your JavaScript file, make an AJAX request to the server using the localized AJAX URL.
jQuery(document).ready(function($) {
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: {
action: 'custom_action',
// Additional data to send
},
success: function(response) {
// Handle the successful response
console.log(response);
},
error: function(errorThrown) {
// Handle the error
console.log(errorThrown);
}
});
});