User Tools

Site Tools


java-script:ajax-fetch

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 (Web Browser)

This code sends a GET request to 'https://api.github.com/users', then prints the data in the web page:

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 a much more cleaner way and also display the avatar image content:

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>

To run it, just double click on the html file, it will be opened in the web browser.

AJAX using the fetch API in JavaScript (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

Then the script should be adapted for node.js:

ajax-fetch-node.js
import fetch from '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));

To run it:

node ajax-fetch-node.js

Using XMLHttpRequest (the traditional AJAX method) to fetch data from a server

We use the XMLHttpRequest object to send a GET request to the GitHub API, just like we did with Fetch API above. We then use the onload event handler to process the response when it's ready. If the request is successful (status code 200), we parse the response text as JSON, and then create some HTML content that displays the user's name, avatar, and url. If the request fails, we log the response text to the console.

Finally, we call the loadUsers function to kick off the AJAX request when the script loads.

This will fetch data from the server without a page reload, in true AJAX style!

fetch-true-ajax-style.html
<!DOCTYPE html>
<html>
<body>
 
<div id="content"></div>
 
<script>
function loadUsers() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", 'https://api.github.com/users', true);
  xhr.onload = function () {
    if (xhr.readyState == 4 && xhr.status == "200") {
      var users = JSON.parse(xhr.responseText);
      var html = '';
      for(var user of users){
        html += `<p>Login: ${user.login}</p>
                 <p>ID: ${user.id}</p>
                 <p>Node ID: ${user.node_id}</p>
                 <img src="${user.avatar_url}" width="50" height="50" />
                 <p>Gravatar ID: ${user.gravatar_id}</p>
                 <p>URL: <a href="${user.url}" target="_blank">${user.url}</a></p>
                 <p>Html URL: <a href="${user.html_url}" target="_blank">${user.html_url}</a></p>
                 <p>Followers Url: ${user.followers_url}</p>
                 <p>Following Url: ${user.following_url}</p>
                 <p>Gists Url: ${user.gists_url}</p>
                 <p>Starred Url: ${user.starred_url}</p>
                 <p>Subscriptions Url: ${user.subscriptions_url}</p>
                 <p>Organizations Url: ${user.organizations_url}</p>
                 <p>Repos Url: ${user.repos_url}</p>
                 <p>Events Url: ${user.events_url}</p>
                 <p>Received Events Url: ${user.received_events_url}</p>
                 <p>Type: ${user.type}</p>
                 <p>Site Admin: ${user.site_admin}</p>
                 <hr>`;
      }
      document.getElementById('content').innerHTML = html;
    } else {
      console.error(xhr.responseText);
    }
  }
  xhr.send();
}
 
loadUsers();
 
</script>
 
</body>
</html>
Node.js can certainly make HTTP requests to APIs or other servers using libraries like axios or node-fetch, or using built-in modules like http or https. These requests are indeed asynchronous, but they're not considered “AJAX requests” because they're not being used to update a web page without a full page refresh.

While both AJAX in the browser and HTTP requests in Node.js involve asynchronous operations, they're used in different contexts and for different purposes. So, it's accurate to say that there's no “true AJAX style” in Node.js, even though Node.js certainly supports asynchronous operations and can make HTTP requests.
java-script/ajax-fetch.txt · Last modified: 2023/08/03 16:33 by odefta