General Assembly Logo


Javascript - AJAX

Get started

Fork and Clone Ajax-Sfoft-Intro

Lesson Objectives

  1. Explain AJAX
  2. Explain promises
  3. Populate the DOM with AJAX data
  4. Make dynamic AJAX requests

Explain AJAX

  • AJAX Stands for Asynchronous JavaScript And XML
  • It's just a way for your page to get data from external sources
<!DOCTYPE html>
<html>
    <head>
      <script defer src="app.js"></script>
    </head>
    <body>

      <h1>Movies!</h1>
      <input type="text" id="movie" placeholder="Enter a movie">
      <input type="submit" id="submit" value="Get Movie Info">
    <div class="movie-screen">

    </div>

    </body>
</html>

We'll have our page get data from the external site http://www.omdbapi.com/.

Let's get Started

  • First, go to http://www.omdbapi.com/ and click on the API Key tab to sign up and get your own API key. Many APIs require a key in order to use their data. Even though OMDB doesn't charge to use their data, they want to prevent misuse.
  • After you have your API key, create your handleSubmit() function. Don't forget 'event.preventDefault()'.
  • Inside your function, grab the input element from your HTML file and set it to a variable so we can pass it to the URL. Follow the URL format that you see above to make a proper fetch request. Make sure to pass it the value! If you do not put '.value' to the end of the line below, you will grab the input box itself, and not what is inside it!

    const movie = document.getElementById('movie')
    const submit = document.getElementById('submit')
    const screen = document.querySelector('.movie-screen')
    
    const handleSubmit = (evt) => {
    evt.preventDefault() // stop page from reloading
    }
    
    submit.addEventListener('click', handleSubmit)

Let's use JavaScript to get data for our page:

const handleSubmit = (evt) => {
  evt.preventDefault() // stop page from reloading
  fetch(`http://www.omdbapi.com/?apikey=${YOUR_API_KEY}&t=${movie.value}`)
    .then(data => {
      return data.json()
    })
    .then(jData => {
      console.log(jData);
    })
    .catch(err => {
      console.log(err);
    })
}
  • fetch() returns a Promise. Next, we have to use then() to manipulate what the Promise returns to us.
  • First we get raw data. In the first then() we use an anonymous function to return data that has been parsed into JSON for us to use.
  • In the next then() we console log our data to see what is inside so we can use what we'd like.
{Title: "Frozen", Year: "2013", Rated: "PG", Released: "27 Nov 2013", Runtime: "102 min",}
{
Actors: "Kristen Bell, Idina Menzel, Jonathan Groff, Josh Gad"
Awards: "Won 2 Oscars. Another 77 wins & 57 nominations."
BoxOffice: "$400,736,600"
Country: "USA"
DVD: "18 Mar 2014"
Director: "Chris Buck, Jennifer Lee"
Genre: "Animation, Adventure, Comedy, Family, Fantasy, Musical"
Language: "English, Norwegian"
Metascore: "74"
Plot: "When the newly-crowned Queen Elsa accidentally uses her power to turn things into ice to curse her home in infinite winter, her sister Anna teams up with a mountain man, his playful reindeer, and a snowman to change the weather condition."
Poster: "https://m.media-amazon.com/images/M/MV5BMTQ1MjQwMTE5OF5BMl5BanBnXkFtZTgwNjk3MTcyMDE@._V1_SX300.jpg"
Production: "Walt Disney Pictures"
Rated: "PG"
Ratings: (3) [{}, {}, {}]
Released: "27 Nov 2013"
Response: "True"
Runtime: "102 min"
Title: "Frozen"
Type: "movie"
Website: "http://www.disney.com/frozen"
Writer: "Jennifer Lee (screenplay by), Hans Christian Andersen (story inspired by "The Snow Queen" by), Chris Buck (story by), Jennifer Lee (story by), Shane Morris (story by)"
Year: "2013"
imdbID: "tt2294629"
imdbRating: "7.5"
imdbVotes: "523,253"
__proto__: Object
}

Populate the DOM with AJAX data

Now that we have successfully made an AJAX request, let's use the response from OMDB to populate the DOM

Let's use JavaScript to manipulate the DOM and append() some data that we got back from our fetch request!

Using the structure in the code above, let's make new elements to populate our page each time a new request is made.

Grab your JSON data from your second 'then' function and pick out the title. Create a new element and append the title from your info.

const handleSubmit = (evt) => {
  evt.preventDefault() // stop page from reloading
  fetch(`http://www.omdbapi.com/?apikey=${YOUR_API_KEY}&t=${movie.value}`)
    .then(data => {
      return data.json()
    })
    .then(jData => {
      let div = document.createElement('div')
      let title = document.createElement('h2')
      title.append(jData.Title)
      div.append(title)
      screen.innerHTML = ''
      screen.append(div)
      movie.value = ''
    })
    .catch(err => {
      console.log(err);
    })
}

Async Await Alternative Syntax

const handleSubmit = async (evt) => {
  evt.preventDefault() // stop page from reloading
  try {
    const data = await fetch(`http://www.omdbapi.com/?apikey=${YOUR_API_KEY}&t=${movie.value}`)
    const jdata = await data.json()
    let div = document.createElement('div')
    let title = document.createElement('h2')
    title.append(jData.Title)
    div.append(title)
    screen.innerHTML = ''
    screen.append(div)
    movie.value = ''
  }catch(err){
    console.log = err
  }
}

LocalStorage

The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

Big Takeaway each website has its own localStorage in the browser, Google cant read localStorage from facebook or netflix

Also localStorage stays behind when a user leaves and comes back, the previous data is in the browser's localStorage

Lets say I wanted to save my movie for later also

const handleSubmit = async (evt) => {
  evt.preventDefault() // stop page from reloading
  try {
    const data = await fetch(`http://www.omdbapi.com/?apikey=${YOUR_API_KEY}&t=${movie.value}`)
    const jdata = await data.json()
    let div = document.createElement('div')
    let title = document.createElement('h2')
    title.append(jData.Title)
    div.append(title)
    screen.innerHTML = ''
    screen.append(div)
    movie.value = ''
    localStorage.setItem('movie', JSON.stringify(jdata))
  }catch(err){
    console.log = err
  }
}

Lets look at the localstorage in our browser console

Question

  • Can we make a save button to save our movie instead of doing it every time?
  • How can we get data out of local storage?
  • Could we create a showLastMovie Button to grab the last movie from the localStorage and store it in the DOM.

Next Steps

  • IndexedDB, Session Storage and Cookies(try not to use these everyone has a law about it one way or the other and the modern web rarely needs them)
  • Add some more info for each movie. Add the Year, Plot, Actors, and Poster.
  • Do this for your 10 favorite movies and when you're finished, add some CSS!
  • When we start Unit 2 our first lesson will be on PROMISES, ASYNC Code, IIFE's and Modules

Additional Resources: