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.

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.

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

Advertisements