jquery - Wordpress admin-ajax.php returns 0 even if using wp_die()
I'm trying to filter my posts with a simple ajax call, but cant get it to work because my admin-ajax.php call always returns 0. There are many issues facing this problem but they are mostly fixed by adding wp_die(), which is not solving my issue.
Ajax Call:
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
action: 'filter_projects',
},
success: function(res) {
$('.project-tiles').html(res);
console.log(res);
}
})
PHP function:
function filter_projects() {
echo "<p>test</p>";
wp_die();
}
add_action('wp_ajax_filter_projects', 'filter_projects');
add_action('wp_ajax_nopriv_filter_projects', 'filter_projects');
The PHP function is registered correctly as I'm getting a 200 on it, but it's always returning 0 and 'success'.
What I already tried:
- WP_DEBUG=1 --> no Error
- Check dev console --> no Error
- Check network --> 200 on admin-ajax.php call but received "0"
- Tried die() and exit instead of wp_die()
I dont know how to debug this any further as it is not returning any errors.
Does anyone have an idea?
Answer
Solution:
instead of echo directly your HTML, try manipulating the results with JSON so you can get better results for evaluating your test. How would I do the same test you posted (using direct JS instead of JQUERY):
let xhr = new XMLHttpRequest();
xhr.open('POST', "/wp-admin/admin-ajax.php", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var params = 'action=filter_projects';
xhr.onreadystatechange = () => {
if(xhr.readyState == 4) {
// RETURN OK
if(xhr.status == 200) {
console.log(xhr.responseText); // TEXT RESPONSE
console.log(JSON.parse(xhr.responseText)); // JSON RESPONSE
// HTTP ERROR
}else{
console.log("SOME ERROR HTTP");
console.log(xhr.responseText);
}
}
};
xhr.send(params);
PHP CODE:
function filter_projects() {
$content = "test";
$data = array('success' => "200", 'content' => $content);
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;
wp_die();
}
add_action('wp_ajax_filter_projects', 'filter_projects');
add_action( 'wp_ajax_nopriv_filter_projects', 'filter_projects' );
Source