1

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.

9
  • 2
    Does this answer your question? 400 bad request on admin-ajax.php only using wp_enqueue_scripts action hook – kero Apr 28 at 9:29
  • No, the request will be made outside the WordPress site. I have a react app that will use most of the backend from WordPress including auth. – TheWhiteFang Apr 28 at 9:47
  • One key aspect in the answer is that the place where the action is added is relevant. In the linked answer this was wrong - are you sure the endpoint itself is working and only calling it from your "non WP" script is the problem? – kero Apr 28 at 9:56
  • 1
    is there a reason you used the old admin-ajax.php API instead of using the modern REST API endpoint system at /wp-json? The REST API tells you what you did wrong in human readable error messages, admin-ajax.php just responds with 0 and no information – Tom J Nowell Apr 28 at 9:59
  • This is likely related to the use of application/json, something that is not an issue if you had used the REST API instead – Tom J Nowell Apr 28 at 10:01
0

When using JS fetch api with the wordpress is set up your issue is with the body.

fetch passes body data in a way that wordpress can't understand.

Your body: {} should be like this

body: new URLSearchParams({
    username: 'thewhitefang',
    password: '@bhishek01',
    action: 'login_ajax'
})

and you need to change your content-type as well. 'Content-Type': 'application/x-www-form-urlencoded'

I can't really explain it well because i never really dived deep into this subject but im sure you could find everything you need about this.

Hope this helps =]

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.