My question is fairly simple. I am working on a project that uses WordPress as a headless CMS(Kinda). I have created an ajax endpoint but it always returns 400. Right now I have created a child theme to test these functionalities. Here's the functions.php that I'm using.
<?php
function login_with_ajax()
{
echo "hey"; exit();
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username) {
echo json_encode(
array(
'status' => false,
'message' => 'Username is required'
)
);
exit();
}
if (!$password) {
echo json_encode(
array(
'status' => false,
'message' => 'Password is required'
)
);
exit();
}
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon($creds, false);
$userID = $user->ID;
wp_set_current_user($userID, $username);
wp_set_auth_cookie($userID, true, false);
do_action('wp_login', $username);
if ( is_user_logged_in() ) {
echo json_encode(
array(
'status' => true,
)
);
} else {
echo json_encode(
array(
'status' => false,
'message' => 'Invalid login credentials'
)
);
}
}
add_action("wp_ajax_nopriv_login_ajax", "login_with_ajax");
I am trying to access it using fetch like this.
fetch('/wp-admin/admin-ajax.php', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'thewhitefang', password: '@bhishek01', action: 'login_ajax' }),
})
Am I doing something wrong?
Edit: This endpoint will not be used in WordPress.
/wp-json
? The REST API tells you what you did wrong in human readable error messages,admin-ajax.php
just responds with0
and no informationapplication/json
, something that is not an issue if you had used the REST API instead