How to create an ajax endpoint without js?

Question

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?

in progress 0
TheWhiteFang 2 years 2021-04-28T04:20:38-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-04-28T22:59:36-05:00

    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'

Leave an answer

Browse
Browse