Jump to content

Get token for ajax request on prestashop


nandosendraa

Recommended Posts

I'm trying to get the token used for the AJAX requests, but I can't

I've tried to

var tokenElement = document.querySelector('input[name="token"]');
return tokenElement ? tokenElement.value : '';

but this returns empty string

My AJAX request is

function updateCartQuantity(productId, newQuantity, direction) {
    var updateCartUrl = 'http://localhost:8080/carrito?update=1&id_product=' + productId + '&id_product_attribute=0&token='+ tokenElement +'&ajax=1&op='+direction ;

    $.ajax({
        type: 'GET',
        url: updateCartUrl,
        success: function (response)
            refreshCart();
        },
        error: function (error) {
            console.error('Error updating:', error);
        }
    });
}

 

But since the variable arrives empty, the request does not work for me, if I put a token written on the js, the request works correctly (I have copied and pasted the token that I use to check that the request works from another request that Prestashop has, but I can't access how this token is generated)

Link to comment
Share on other sites

Hi,

In Prestashop, the token for AJAX requests is usually generated dynamically and associated with the user's session to enhance security. Instead of trying to directly retrieve the token from the DOM, you should fetch it from PrestaShop's context.

Try:

// Fetch the token from PrestaShop's context
var token = window.prestashop.static_token;

I hope this helps!

Thanks!

  • Thanks 1
Link to comment
Share on other sites

2 hours ago, AddWeb Solution said:

Hi,

In Prestashop, the token for AJAX requests is usually generated dynamically and associated with the user's session to enhance security. Instead of trying to directly retrieve the token from the DOM, you should fetch it from PrestaShop's context.

Try:

// Fetch the token from PrestaShop's context
var token = window.prestashop.static_token;

I hope this helps!

Thanks!

Thanks a lot, it works, but how you found that, I was searching on the prestashop dev docs but I can't found that

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...