Ajax Get Call In Javascript Example

5 min read Jun 22, 2024
Ajax Get Call In Javascript Example

AJAX GET Call in JavaScript Example

AJAX (Asynchronous JavaScript and XML) is a powerful technique used in web development to make requests to a server without reloading the entire page. This allows for dynamic content updates, improved user experience, and faster web applications.

In this example, we'll demonstrate a simple AJAX GET call in JavaScript to fetch data from a server and display it on the webpage.

1. HTML Structure

First, we'll set up a simple HTML structure to hold our data:




  AJAX GET Example



  

We have a <div> element with the id "data" where we'll insert the fetched data.

2. JavaScript Code (script.js)

Now, let's write the JavaScript code to handle the AJAX request:

const dataDiv = document.getElementById('data');

// Function to make the AJAX GET request
function fetchData() {
  const url = "https://example.com/api/data"; // Replace with your API endpoint

  // Create a new XMLHttpRequest object
  const xhr = new XMLHttpRequest();

  // Open a GET request to the specified URL
  xhr.open("GET", url);

  // Set the response type
  xhr.responseType = "json"; // Assuming the response is JSON

  // Handle the response
  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
      // Successful request
      const data = xhr.response; // Extract the data from the response

      // Display the data in the dataDiv
      dataDiv.innerHTML = `
        

Data from API

    ${data.map(item => `
  • ${item.name}: ${item.value}
  • `).join('')}
`; } else { // Handle errors console.error("Error fetching data:", xhr.status); dataDiv.innerHTML = "An error occurred while fetching data."; } }; // Send the request xhr.send(); } // Call the fetchData function fetchData();

Explanation:

  • const dataDiv = document.getElementById('data');: This line selects the div element with the ID "data" for displaying the data.
  • function fetchData() { ... }: This function contains the logic for making the AJAX request.
  • const url = "https://example.com/api/data";: Replace this with your actual API endpoint URL.
  • const xhr = new XMLHttpRequest();: Creates a new XMLHttpRequest object, which is responsible for sending the request.
  • xhr.open("GET", url);: Opens a GET request to the specified URL.
  • xhr.responseType = "json";: Sets the response type to JSON, as we're expecting JSON data.
  • xhr.onload = function() { ... }: This function is executed when the request is completed.
  • if (xhr.status >= 200 && xhr.status < 300) { ... }: Checks if the request was successful (status code between 200 and 300).
  • const data = xhr.response;: Extracts the JSON data from the response.
  • dataDiv.innerHTML = ...: Updates the content of the "data" div with the fetched data.
  • else { ... }: Handles errors if the request fails.
  • xhr.send();: Sends the request to the server.

3. Running the Example

  1. Save the HTML code as "index.html" and the JavaScript code as "script.js" in the same directory.
  2. Open "index.html" in your web browser.
  3. The data from the specified API endpoint will be fetched and displayed in the "data" div.

Note:

  • Make sure to replace "https://example.com/api/data" with your actual API endpoint URL.
  • The example assumes the API endpoint returns JSON data. You may need to adjust the response handling based on your API's response type.

This basic example demonstrates the core functionality of AJAX GET calls. You can further extend it by using libraries like jQuery or Axios for simpler and more efficient AJAX handling.

Related Post


Latest Posts