Submitting and Handling AJAX Requests in Aptuitiv

You can use any Javascript framework to submit an AJAX request to your website to fetch data and your templates can detect if an AJAX request was made. 

The platform detects an AJAX request based on one of two conditions:

  1. The X_REQUESTED_WITH header is present, and its value is "XMLHttpRequest".
  2. The CONTENT-TYPE header is set to "application/json".

Some Javascript libraries like jQuery or axios set one or both of these headers automatically. However, if you use fetch then you'll need to manually set one of the headers. 

This is a basic example of setting the X_REQUESTED_WITH header with fetch.

<script>
fetch('/some-url', {
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
    }
})
</script>

Alternatively, you can set the Content-Type header in fetch.

<script>
fetch('/some-url', {
    headers: {
        'Content-Type': 'application/json',
    }
})
</script>

Detecting AJAX requests in your templates

You can use the _page.request.isAjax variable in your Twig templates to detect if the request was an AJAX request.

{% if _page.request.isAjax %}
    It's an Ajax request!
{% endif %}
This documentation is only for Aptuitiv CMS. Learn more.
Get Started With Aptuitiv