How to get JSON data using Ajax Javascript

To get JSON data using Ajax in JavaScript, you can use the `XMLHttpRequest` (XHR) object, or the newer `fetch()` API. Here's an example using the XHR object:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json', true);

xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 400) {
    let data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error('Error getting data:', xhr.statusText);
  }
};

xhr.onerror = function() {
  console.error('Error getting data:', xhr.statusText);
};

xhr.send();

 

In this example, we create a new `XMLHttpRequest` object, set the HTTP method to GET, and specify the URL of the JSON data we want to fetch. We then define an `onload` event handler function that will be called when the response is received. Inside this function, we check the HTTP status code to make sure the response was successful (in the 200-399 range), and then use `JSON.parse()` to convert the JSON string into a JavaScript object.

If the response is not successful, we log an error message to the console. We also define an `onerror` event handler function that will be called if there is an error while fetching the data.

Using the `fetch()` API, the code would look like this:

fetch('https://example.com/data.json')
  .then(response => response.json())
  .then(data => console.log(data))

  .catch(error => console.error('Error getting data:', error));

In this example, we call the `fetch()` function with the URL of the JSON data we want to fetch. We then chain a `.then()` method to the response, which uses the `json()` method to convert the response into a JavaScript object. We then chain another `.then()` method to log the data to the console, and a `.catch()` method to handle any errors that may occur.

Previous Post Next Post