How to update data in AJAX with JSON

AJAX(Asynchronous JavaScript And XML) is a set of web development techniques that use client-side web technologies to create asynchronous web applications.

With AJAX, web applications can asynchronously send and retrieve data from a server without interfering with the existing page’s display and behavior.

AJAX is not a programming language; it requires a built-in browser with the XMLHttpRequest object, which requests data from the server. It also uses JavaScript and HTML DOM to display the data.

Ajax JSON

JSON is a common file format used to pass updates between clients and servers. For example, imagine you are watching a baseball match where the Yankees are playing the Red Sox. At this game, the live score may be updated on a website by storing the data on the server. This data can be retrieved whenever it is required, which is why websites may use JSON formatted data.

Any data that is updated using AJAX can be stored using the JSON format on the web server.

AJAX is used so that javascript can retrieve these JSON files when necessary and parse them. Furthermore, they can perform the following functions:

  1. Store the parsed values in the variables for further processing before displaying them on the webpage.

  2. It directly assigns the data to the DOM elements in the webpage so that they are displayed on the website.

Code

Look at the code below, which updates the football match score between Barcelona and Real Madrid:

Now, given that the browser receives the updated score after every minute as a JSON file in data.json file in the browser, the updated score file may look like this after one minute:

{"score": "1-0", "time": "53 min"}

Now, when you click on the button Check updated score, the score will be updated. The output looks like this:

Well, looks like Barcelona Scores!!!

Copyright ©2024 Educative, Inc. All rights reserved