AJAX Flashcards
What does XHR Stand For?
XMLHttpRequest object
What is XHR?
The XMLHttpRequest object is a JS API that allows us to transfer data between a client and a server and update parts of a page without refreshing
What type of data is the standard to be used with XHR?
JSON - JavaScript Object Notation
Add an HTML link that will use XHR to getRepositories( )
<div>
<h3>Repositories</h3>
<a>Get Repositories</a>
</div>
Create a getRepositories function and initiate our XHR request.
function getRepositories() {
const req = new XMLHttpRequest();
req.addEventListener(‘load’, showRepositories);
req.open(‘GET’, ‘https://api.github.com/users/octocat/repos’);
req.send();
}
Here, we’re creating a new instance of an XMLHttpRequest. We call open with the HTTP verb we want, in this case GET, and the URI for the request.
Now that our request is set up and ready to go, we call send to make it happen.
Add an event listener with a callback function that will get called when the event fires.
function getRepositories() {
const req = new XMLHttpRequest();
req.addEventListener(‘load’, showRepositories);
req.open(‘GET’, ‘https://api.github.com/users/octocat/repos’);
req.send();
}
function showRepositories() { //this is set to the XMLHttpRequest object that fired the event console.log(this.responseText); }
Create a getCommits REQUEST function that listens for a response
function getCommits(el) {
const name = el.dataset.repo;
const req = new XMLHttpRequest();
req.addEventListener(‘load’, showCommits);
req.open(‘GET’, ‘https://api.github.com/repos/octocat/’ + name + ‘/commits’);
req.send();
}
Create a showCommits function that shows the response
function showCommits() { const commits = JSON.parse(this.responseText); const commitsList = `<ul>${commits .map( commit => '<li><strong>' + commit.author.login + '</strong> - ' + commit.commit.message + '</li>' ) .join('')}</ul>`; document.getElementById('commits').innerHTML = commitsList; }
Create a place in HTML to put the commits
<div>
<h3>Commits</h3>
<div></div>
</div>
What does jQuery do?
Abstracts XHR into easier, higher-level \code
What Does AJAX stand for?
Asynchronous JavaScript and XML
What does AJAX do?
What’s the diff between XHR, AJAX & Jquery?
XMLHttpRequest is raw object for ajax request. It is lightest performance wise but it is not cross-browser compatible so using this you will loose cross-browser accessability for your Asynchronous request while $.ajax() is provided by jquery that adds cross-browser compatibility to asynchronous request
Give an example of how we could use jQuery to perform an Ajax request.
var url = 'https://api.github.com/repos/rails/rails/commits?sha=82885325e04d78fb7ec608a4670164d842d23078';
$.get(url).done(function(data) {
console.log(‘Done’);
console.log(data);
});
How to use jQuery,get()
https://api.jquery.com/jquery.get/