How to Create a Basic AJAX Request

Published on: May 14, 2017

Welcome to the 47th Easy JavaScript tutorial, part of EasyProgramming.net. I gave you a brief intro to what AJAX is and showed you a quick example at the end. Today we're going to cover one of those examples and create a very basic AJAX event on your webpage. Here you will click a button and using AJAX, your web page will update with content located in another file. 

One thing you will need to know is that you can only run this from a web server. You can't open the file directly on your browser and try it, it won't work. That's why I'm using brackets because it allows for a preview. 

To follow along this tutorial (and the next), 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/

As mentioned in the presentation last week, you only need three main components for a successful AJAX request. They are:

    var xhr = new XMLHttpRequest(); //creates a new ajax request and assigns to variable xhr
    xhr.open("METHOD","url",true); //opens the xhr request passing in three arguments: the method (get/post), url, and true/false for asynchronous/synchronous
    xhr.send(); // make the AJAX request

 Ready to star coding? Watch the video below and follow along!

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:

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. 

 



Comments: