Skip to content

Conversation

@tijsverkoyen
Copy link
Member

AJAX client

The AJAX client is a simple wrapper around Axios.

Default Axios Config

Some configuration is done by default. But it can be overruled.

  • timeout: 2500
  • headers.common: Accept: application/json

Usage

Is the AJAX Client is just an extended version of the Axios client all Axios
documentation is still valid. For the full documentatuon see
https://axios-http.com/docs/intro.

A simplified Stimulus controller that uses the AJAX Client:

import { Controller } from '@hotwired/stimulus'
import ajaxClient from '../js/ajax_client.js'

export default class extends Controller {
  static values = {
    url: String,
    csrfToken: String
  }

  test () {
    let data = {
      foo: 'bar',
    }

    ajaxClient.csrf_token = this.csrfTokenValue
    ajaxClient.post(this.urlValue, data)
      .then(response => {
        // do something with the response
      ...
      })
      .catch(error => {
        // do something with the error
      ...
      })
  }
}

Default toasts

Depending on HTTP status code and the provided data a toast will be shown. This
is done by using Interceptors. So
you can still use the promises of the Axios client.

Success (HTTP Status 2XX)

If the response object contains a message key, a success toast will be shown.

You can return a response like this:

  return new JsonResponse(
    [
      'message' => 'The action was successful.',
    ],
    200
  );

The actual JSON will be:

{
  "message": "The action was successful."
}

Error (HTTP Status != 2XX)

If the response object contains a message key, an danger toast will be shown.
If the message is not present the Exception message will be used.

  return new JsonResponse(
    [
      'message' => 'Item not found.',
    ],
    404
  );

or

  throw new \RuntimeException('Item not found.');

Disable this behavior

You can disable the toast by passing a disable_interceptor: false in the response data.

{
  "message": "The action was successful",
  "disable_interceptor": true
}

CSRF token

A simple way to "protect" the AJAX calls is by using a CSRF token. This is done like below:

ajaxClient.csrf_token = this.csrfTokenValue
ajaxClient.post(this.urlValue, data)
  ...

With this the csrf token is added to the payload of the request, with the key csrf_token.

In your controller you will need to check if the CSRF token is valid:

  if (!$this->isCsrfTokenValid('this-is-our-csrf-token-id', $request->getPayload()->get('csrf_token'))) {
    throw new InvalidCsrfTokenException('Invalid CSRF token');
  }


## Usage

Is the AJAX Client is just an extended version of the Axios client all Axios
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hier staat een 'is' te veel :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cc3b697

@tijsverkoyen tijsverkoyen merged commit 70de2d1 into master Jan 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants