How to create an ajax endpoint without js?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 =]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x