This is an old revision of the document!
−Table of Contents
Ajax fetch example
AJAX (Asynchronous JavaScript and XML) and async JavaScript both deal with asynchronous behavior in JavaScript, but they are used for different things.
AJAX is a technique that allows a web page to communicate with a server and update its content without refreshing the page. AJAX can be done using vanilla JavaScript (usually with the XMLHttpRequest object or fetch API) or with a library like jQuery (using the $.ajax() function).
AJAX using the fetch API in JavaScript in Web Browser
This code sends a GET request to 'https://api.github.com/users', then logs the returned data to the console.
- ajax-fetch.html
<!DOCTYPE html> <html> <body> <h1>Fetch API Example</h1> <div id="data"></div> <script> fetch('https://api.github.com/users', { method: 'GET', }) .then(response => response.json()) .then(data => { // Convert the data to a string, so we can put it into the HTML // This may vary depending on the structure of your data let dataStr = JSON.stringify(data, null, 2); // Find the div by its ID, and put the data into it document.getElementById('data').textContent = dataStr; }) .catch((error) => console.error('Error:', error)); </script> </body> </html>
The following script will display the data in the web page (instead of console) and format it a bit:
- ajax-fetch-format.html
<!DOCTYPE html> <html> <body> <h1>Fetch API Example</h1> <div id="data"></div> <script> fetch('https://api.github.com/users', { method: 'GET', }) .then(response => response.json()) .then(data => { let dataDiv = document.getElementById('data'); data.forEach(user => { let userDiv = document.createElement('div'); // create a string that represents all key-value pairs in the user object let userInfo = ''; for (let key in user) { userInfo += `<p><strong>${key}</strong>: ${user[key]}</p>`; } // add this userInfo to userDiv userDiv.innerHTML = ` <h2>${user.login}</h2> <img src="${user.avatar_url}" alt="${user.login}'s avatar" width="50"> <div>${userInfo}</div> `; dataDiv.appendChild(userDiv); }); }) .catch((error) => console.error('Error:', error)); </script> </body> </html>
AJAX using the fetch API in JavaScript in Node.js
We'll need to use node-fetch instead of fetch.
To install it:
npm install node-fetch
Output:
added 6 packages, and audited 7 packages in 1s 3 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
The the script should be adapted for node.js:
- ajax-fetch-node.js
const fetch = require('node-fetch'); fetch('https://api.github.com/users', { method: 'GET', }) .then(response => response.json()) .then(data => { data.forEach(user => { console.log('Login: ', user.login); console.log('ID: ', user.id); console.log('Node ID: ', user.node_id); console.log('Avatar URL: ', user.avatar_url); console.log('Gravatar ID: ', user.gravatar_id); console.log('URL: ', user.url); console.log('HTML URL: ', user.html_url); console.log('Followers URL: ', user.followers_url); console.log('Following URL: ', user.following_url); console.log('Gists URL: ', user.gists_url); console.log('Starred URL: ', user.starred_url); console.log('Subscriptions URL: ', user.subscriptions_url); console.log('Organizations URL: ', user.organizations_url); console.log('Repos URL: ', user.repos_url); console.log('Events URL: ', user.events_url); console.log('Received Events URL: ', user.received_events_url); console.log('Type: ', user.type); console.log('Site Admin: ', user.site_admin); console.log('\n----------\n'); }); }) .catch((error) => console.error('Error:', error));