json
  1. ajax-json-introduction

AJAX with JSON

  • AJAX (Asynchronous JavaScript and XML) is a technology that allows web pages to be updated asynchronously by exchanging small amounts of data with the server without reloading the entire page.
  • JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

Syntax

To make an AJAX request with JSON data, we can use the following syntax:

$.ajax({
   url: 'url-to-server-api',
   type: 'POST/GET',
   dataType: 'json',
   data: JSON.stringify({ key: value }),
   success: function(data) {
      // do something with the data
   },
   error: function(xhr, status, error) {
      // handle errors
   }
});
  • url: The URL of the server API that we want to send the JSON data to.
  • type: The type of request (POST or GET).
  • dataType: The type of data to expect back from the server (json).
  • data: The JSON data that we want to send to the server.
  • success: A callback function that is called when the request is successful.
  • error: A callback function that is called when the request fails.

Example

Here is an example of how we can use AJAX with JSON to fetch data from a server:

$.ajax({
   url: 'https://jsonplaceholder.typicode.com/posts',
   type: 'GET',
   dataType: 'json',
   success: function(data) {
      console.log(data);
   },
   error: function(xhr, status, error) {
      console.log(error);
   }
});

This code sends a GET request to the URL https://jsonplaceholder.typicode.com/posts and expects a JSON response. When the response is received, the callback function success logs the data to the console. If an error occurs, the callback function error logs the error message to the console.

Output

The output of the example code above would be an array of objects representing posts:

[
   {
      "userId": 1,
      "id": 1,
      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
      "body": "quia et suscipit\nsuscipit..."
   },
   {
      "userId": 1,
      "id": 2,
      "title": "qui est esse",
      "body": "est rerum tempore vitae\nsequi sint..."
   },
   // ...
]

Explanation

In the example code above, we use the $.ajax() function to make an AJAX request to the server API https://jsonplaceholder.typicode.com/posts. This API returns JSON data representing posts.

We set the dataType option to 'json' to tell jQuery that we are expecting JSON data back from the server.

In the success callback function, we log the data object to the console. This data object contains the JSON data returned by the server API.

Use

AJAX with JSON can be used to fetch data from a server API, update data on the server, or delete data from the server. This makes it a powerful tool for creating dynamic web applications that can update data on-the-fly without the need for a full page refresh.

AJAX with JSON is also popular for integrating with third-party APIs that provide JSON data, such as social media APIs, weather APIs, and financial data APIs.

Important Points

  • Use the $.ajax() function to make an AJAX request with JSON data.
  • Set the dataType option to 'json' to expect JSON data back from the server.
  • Use the JSON.stringify() method to convert a JavaScript object to a JSON string before sending it to the server.
  • Use the JSON.parse() method to convert a JSON string to a JavaScript object after receiving it from the server.
  • Use callback functions to handle successful and failed requests.

Summary

AJAX with JSON is a powerful way to fetch data from a server API and update data on-the-fly in a web application. It allows web pages to be updated asynchronously without the need for a full page refresh, providing a smoother and more responsive user experience. By using the $.ajax() function along with the JSON.stringify() and JSON.parse() methods, we can easily make AJAX requests with JSON data and handle the results in JavaScript code.

Published on: