Stimulus and Ajax

Learn to use Stilumus and Ajax in this lesson.

We'll cover the following

Usually, when we talk about communication between the client and server, we are referring to the client calling the server to receive data. Let’s look at how we would make those calls in our Stimulus code.

Making Ajax calls

The simplest mechanism for making Ajax calls in modern JavaScript is with the fetch function and the async/await syntax for handling asynchronous behavior.

The Rails UJS library provides an ajax method, but the fetch function is a little easier to integrate with more modern JavaScript because the Rails ajax method does not use JavaScript Promises.

The fetch method takes two arguments: the URL to contact, and an object containing optional arguments, like method for HTTP method, body, and so on.

The return value for fetch is a Response object wrapped in a JavaScript promise. A promise is a JavaScript object that represents an asynchronous process that will eventually result in some data. Calling the then method on the promise object allows a function to be invoked only when the process has ended successfully.

If you’ve written JavaScript code in the last few years, you might be familiar with this pattern:

updateData() {
  fetch("/sold_out_concerts").then (response) => {
	  response.text().then (text) => {
	    // do something with text
	  }
  }
}

In cases where multiple asynchronous events need to happen, the sequence of then calls on the various promises can get complicated, and so the async and await keywords were introduced to simplify using asynchronous processes:

asnyc updateData() {
  const response = await fetch("/sold_out_concerts")
  const text = await response.text()
  // do something with text
}

The async keyword marks the updateData function as being able to handle await keywords inside it. Within an async function, the await keyword expects a promise as its argument, and the code waits there until the promise resolves. In this case, a successful fetch returns a response wrapped in a promise, and by using await, the code sits in place until the response is received. Similarly, response.text also returns a promise, and we again await the response before the code flows forward.

Get hands-on with 1400+ tech skills courses.