rekzi
rekzi

Reputation: 23

Why WP AJAX always return 0?

Tried to get answer, but returns 0. JS in the head:

q = new XMLHttpRequest();
q.open('POST', ajaxUrl);
q.onreadystatechange = function () {
    if (q.readyState === 4) {
        console.log(q.response);
    }
};

var data = {
    'action': 'check_email'
};
q.send(JSON.stringify(data));

ajaxUrl links to admin_url('admin-ajax.php'); Code in the function.php:

function check_email() {
    echo 'true or false';
    die();
}
add_action('wp_ajax_check_email', 'check_email');
add_action('wp_ajax_nopriv_check_email', 'check_email');

Upvotes: 1

Views: 134

Answers (2)

Musa
Musa

Reputation: 97672

Assuming a json request is valid, set the content-type to json

q.setRequestHeader('Content-Type', 'application/json');

if it isn't send application/x-www-form-urlencoded instead

q.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
...
q.send('action=check_email');

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

q.responseText is what you're looking for.

Upvotes: 0

Related Questions