You're viewing the documentation of an older Simple Commerce version. Consider upgrading to the latest for new features and bug fixes.

Using with AJAX

  1. # Endpoints
  2. # CSRF
  3. # Example

Normally, you can use Simple Commerce's form tags to build HTML <form> elements to do actions, such as adding to the cart or submitting a user's payment information during checkout.

However, sometimes you may want to use AJAX instead of forms as you don't need to wait for a page refresh after submitting data.

Submitting via AJAX is totally possible, it just takes a little bit more effort on your end when building your sites.

Endpoints

Each of the form tags point to different endpoints.

The easiest way to figure out which endpoint you want to use in place of a form tag would be to use the form tag temporarily in your template and grab the outputted form action.

If you're super duper interested, here's the routes file, in case there's any 'hidden' routes we don't provide a tag for (spoiler: there's a couple).

You can send any of the same parameters to the endpoints as documented in the respective tag.

Instead of returning redirects when you submit actions, a JSON response will be returned, containing the request status, a message and any assosiated resources, like the current cart.

1{
2 "status": "success",
3 "message": "Cart Updated",
4 "cart": {...}
5}

CSRF

CSRF is a feature of Laravel which essentially helps to prevent request spoofing by providing a token only available to the current user's specific session.

When making POST/DELETE requests to Simple Commerce endpoints, remember to provide a _token parameter with a CSRF token.

1let params = {
2 '_token': '{{ csrf_token }}'
3}

Example

Here's a quick & basic example of using Axios to make an HTTP request to one of Simple Commerce's endpoints.

1let params = {
2 '_token': '{{ csrf_token }}',
3 'product': 'your-product-id',
4 'quantity': 1
5}
6 
7axios.post('/!/simple-commerce/cart-items', params)
8 .then((response) => {
9 console.alert('Whoop! The product has been added to your cart')
10 })
Last updated 3 months ago Improve this page on GitHub!