Ajax querry returns error 400 but only when user is logged in

[ad_1]

We are currently developing a custom made theme from scratch.

However, when trying to debug Ajax queries, we found an issue that we have not been able to investigate much further:

Running any Ajax query if the login cookies are set returns an error 400.

But if we remove the login cookies, the queries no longer return the error 400.

This is the (simplified) code JS side:


jQuery.ajax({
        url: my_ajax_object.ajaxurl,
        type: 'POST',
        data: {
            action: 'shop-query',
            queryParams: JSON.stringify(params)
        },
        accept:'application/json',
        cache: false,
        contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
        success: response =>{/*Modify page*/},
        error: (xhr, textStatus, error) => {
            console.log(error);
        }
    });

This is the code which is called php side:


if (!isset($_POST["queryParams"])) wp_send_json_error("No query params provided");
$queryParams = json_decode(stripslashes($_POST["queryParams"]), true);

$products = queryPosts::shopQuery($queryParams);

$page = $queryParams['page'] ?? 1;
$total = $queryParams['total'] ?? 9;

$startIndex = ($page - 1) * $total;
$endIndex = $startIndex + $total;
if ($startIndex === $endIndex) $endIndex = $startIndex + 1;

$min_max = getMinAndMaxPrice($products);

ob_start();
for ($i = $startIndex; $i < $endIndex; $i++) {
    if (!isset($products[$i])) break;
    get_template_part('woocommerce/content', 'product', array(
        'product' => $products[$i]
    ));
}

wp_send_json_success(array(
    'html' => ob_get_clean(),
    'found_total' => count($products),
    'min' => $min_max['min'],
    'max' => $min_max['max']
));

The add_action call is situated at the end of the functions.php file, and moving it does not seem to resolve this issue.

As stated above, when no login cookie is set, the query has no issue, which is not an issue I was able to find anywhere else.

I thank you for the help you might be able to provide, this has been quite the headache.

EDIT: echo-ing the $_POST parameters prints them alongside the 0 of the error 400, but echo-ing inside the callback does nothing, the parameters are received but the php callback is never called.

EDIT 2: Turns out all I needed to do was add a normal add action bellow the nopriv add action… Not deleting this thread in case anyone runs into the same problem.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer