I have been working in a project and I hit a road block from admin-ajax.php file, when i make an ajax request it returns 400 error bad request and the admin-ajax.php response in the network tab is 0.
script.js
$.ajax({
url: city_generator.ajax_url,
type: 'POST',
data: {
nonce: city_generator.nonce,
action: 'load_counties',
state: state,
},
success: function (response) {
console.log('County response:', response);
},
error: function (error) {
console.error('Error loading counties:', error);
},
});
and inside my admin-page.php
/ Example: Load counties based on state
add_action('wp_ajax_load_counties', 'load_counties_callback');
add_action('wp_ajax_nopriv_load_counties', 'load_counties_callback');
function load_counties_callback() {
$nonce = $_POST['nonce'];
check_ajax_referer('ajax-nonce', 'nonce'); // Verify the nonce
if (isset($_POST['state'])) {
$state = sanitize_text_field($_POST['state']);
$counties = get_counties_by_state($state);
wp_send_json_success(array('counties' => $counties));
}
wp_die();
}
and also in my city-generator.php
add_action('admin_enqueue_scripts', 'city_generator_admin_enqueue_scripts');
function city_generator_admin_enqueue_scripts($hook) {
if ($hook === 'settings_page_city-generator') {
wp_enqueue_script('city-generator-script', plugin_dir_url(__FILE__) . 'assets/script.js', array('jquery'), null, true);
wp_enqueue_style('city-generator-style', plugin_dir_url(__FILE__) . 'assets/style.css');
wp_localize_script('city-generator-script', 'city_generator', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce'),
));
}
}
and the error I get in the console is
load-scripts.php?c=1…e,utils&ver=6.5.2:2
POST http://localhost/mywordpress/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
script.js:26 Error loading counties:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort
:
ƒ (e)
always
:
ƒ ()
catch
:
ƒ (e)
complete
:
ƒ ()
done
:
ƒ ()
error
:
ƒ ()
fail
:
ƒ ()
getAllResponseHeaders
:
ƒ ()
getResponseHeader
:
ƒ (e)
overrideMimeType
:
ƒ (e)
pipe
:
ƒ ()
progress
:
ƒ ()
promise
:
ƒ (e)
readyState
:
4
responseText
:
"0"
setRequestHeader
:
ƒ (e,t)
state
:
ƒ ()
status
:
400
statusCode
:
ƒ (e)
statusText
:
"Bad Request"
success
:
ƒ ()
then
:
ƒ (t,n,r)
[[Prototype]]
:
Object
please help. Thank you