Welcome to the 48th Easy JavaScript tutorial, part of EasyProgramming.net. In the last tutorial, we covered some simple AJAX requests. Lets get deeper and do a little bit more, this time, let's read some JSON data that we will call asynchronously with a button click via an AJAX call.
As mentioned in the presentation last week, you only need three main components for a successful AJAX request. They are a new XMLHttpRequest
item, open the XHR, and send the XHR. In today's tutorial, we cover a few more things such as the readState
and the responseText
:
var xhr = new XMLHttpRequest(); element.addEventListener("click",function(){ xhr.addEventListener("readystatechange",function(){ if(this.readyState == 4 && this.status == 200){ var data = JSON.parse(d.responseText); //parse and display data } }); xhr.open('METHOD','url',true); xhr.send(); });
To follow along this tutorial, go over to the following page and download the files. You can view page source to get the HTML and JavaScript: https://www.easyprogramming.net/downloads/javascript/ajax/
Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!
Go to the following url to download the exercise files and follow along: https://www.easyprogramming.net/downloads/javascript/ajax/
Have questions? Ask in the comments section on YouTube or Disqus below.