Salesforce: Make Ajax calls with Lightning Components

LockerService has been a source of frustration for many Lightning component developers. But the fact remains that LockerService is here to stay. It’s an important part of security in when using Lightning components from different sources.

LockerService is not just bad news. Now that it’s mandatory, developers can use many long-awaited features. One of those is making Ajax calls directly from Lightning components. This blog will walk you through a demo of making an AJAX call to Google APIs to get information about a location.

Let’s start by going to SetupCSP Trusted Sites and adding https://maps.googleapis.com as a trusted site. This will allow a Lightning component to make a call to this domain and get information back.

First I decided to build a utility component that can be called from any component to make an Ajax call and process result. Feel free to use this component for demo or actual use as needed.

Utils.cmp

UtilsController.js

XMLHttpRequest.cmp

XMLHttpRequestController.js

XMLHttpRequestHelper.js

On success, you should see return response from maps.googleapis.com for provided address.

This is a very welcome change and will solve many issues now that we can make calls directly from Lightning components. I came across it this week and wanted to test and share it here.

Note: Source code used in this blog is available at https://github.com/jrattanpal/Blog-LC-Ajax

Leave a Reply

Your email address will not be published. Required fields are marked *