TransWikia.com

Get a list of countries available for shipping with Ajax in Craft Commerce

Craft CMS Asked on January 14, 2021

I need to fetch a list countries available for shipping in Craft Commerce.

The problem is that I use decoupled frontend on Nuxt.js and I need fetch it with Ajax call and not with the twig code.

I tried to call it in a Postman but it returns me a 403 – Forbidden error with message "User is not permitted to perform this action".

I couldn’t find something about the way of making request through Ajax in Commerce documentation, can you please tell me what I’m doing wrong here?

enter image description here

3 Answers

You need to provide a CSRF token, alternatively turn it off in your config/general.php file.

Set a token in your twig template:

{% set csrfToken = {
    csrfTokenName: craft.app.config.general.csrfTokenName,
    csrfTokenValue: craft.app.request.csrfToken,
} %}

<script type="text/javascript">
    window.Craft = {{ csrfToken|json_encode|raw }};
</script>

Then include the CSRF token name and value in your post array (data):

data[window.Craft.csrfTokenName] = window.Craft.csrfTokenValue;

Alternatively you can set enableCsrfProtection to false in your general config file.

Answered by Syversen on January 14, 2021

The controller action you are hitting returns a template and I think that it is why you are getting this error.

If you don't have headlessMode on (docs) you could make a quick template, add:

{% header "Content-Type: application/json"%}
{{ craft.commerce.countries.getAllCountries() | json_encode() | raw }}

Which would give you an endpoint you can then reach from your front end.

Alternatively, you could make a small module/plugin with a controller.

Answered by Oli on January 14, 2021

After enabling the headless mode in Craft I'm getting the same error in JSON format:

enter image description here

Anyway I guess I have to write some module for that extra functionality. Thank you for the tips!

Answered by Oleksandr Staniev on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP