Laravel have bundled Axios in with their framework. I didn’t know what this was at first and didn’t use it. But once I figured out what it was for I tried to make a gradual change in coding to start using it.

The simplest way I can describe it is as a promise based replacement for jQuery $.ajax() for XHR submissions.

The change to axios from $.ajax() is quite straightforward. You’ll find some axios references in your bootstrap.js file that sets up the CSRF-TOKEN​. I also added in here a similar function for handling CSRF with jQuery.

/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
require('es6-promise').polyfill();
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
// Add the csrf token to both axios calls and jquery ajax calls
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token.content
}
});
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

view raw
app.axios.js
hosted with ❤ by GitHub

The use of axios follows a logical syntax and is easy to follow.

  axios.get('/url')
    .then(function(response) {
      var options = [];
      $(response.data.options).each(function(index, item) {
        options.push('' + item.name + '');
      });
      $('#select').append(options.join(''));
    })
    .catch(function(error) {
      console.log(error);
    });

Which is so close to the $.ajax() function as to be almost a drop in.

My problem came when I tried to submit a form with form data using XHR and axios. I spent ages trying to generate the form data using new FormData() and iterating fields and couldn’t get Laravel to see the Request data correctly.

Then I just serialized the form and passed that as the data parameter in my axios.put() command.

$('#form').on('submit', function(e) {
axios.put('/url', $(this).serialize())
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
e.preventDefault();
});

view raw
axios-formdata.js
hosted with ❤ by GitHub

IE11 Promise is ‘undefined’

With older non-HTML5/Promise capable browsers you’ll need to polyfill() the Promise statement by installing and requiring es6-promise including the following line in your bootstrap.js:

$ npm install es6-promise --save-dev

bootstrap.js

require('es6-promise').polyfill();

References

https://github.com/stefanpenner/es6-promise