Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • jQuery Tutorial
  • jQuery Selectors
  • jQuery Events
  • jQuery Effects
  • jQuery Traversing
  • jQuery HTML & CSS
  • jQuery AJAX
  • jQuery Properties
  • jQuery Examples
  • jQuery Interview Questions
  • jQuery Plugins
  • jQuery Cheat Sheet
  • jQuery UI
  • jQuery Mobile
  • jQWidgets
  • Easy UI
  • Web Technology
Open In App
Next Article:
How to fetch data from a local JSON file in React Native ?
Next article icon

How to load a JSON object from a file with ajax?

Last Updated : 25 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Loading a JSON object from a file using AJAX involves leveraging XMLHttpRequest (XHR) or Fetch API to request data from a server-side file asynchronously. By specifying the file's URL and handling the response appropriately, developers can seamlessly integrate JSON data into their web applications. This method enables dynamic loading of data without requiring a page refresh, facilitating responsive and interactive user experiences.

JSON (JavaScript Object Notation) is a simple and lightweight format used to exchange data between servers and different parts of an application. It is easy for both humans and machines to understand and execute. With its simplified and structured approach, JSON makes sending and retrieving data between client and server sides easy.

Approaches

AJAX Approaches:

  • Using XMLHttpRequest (XHR): This is a basic AJAX approach.
  • Using Fetch API: Fetch API is a modern replacement of XHR but still is an AJAX based approach.
  • Using JQuery: provides a simplified AJAX based approach using '$'.
  • Using Axios: Axios is an another important library for making AJAX requests.

Non-AJAX Approaches:

  • Using Node.js: This is mainly for server side javaScript using Node.js that does not involve the communication with client side via HTTP.

Table of Content

  • Using XMLHttpRequest (XHR)
  • Using JQuery

example.json File


{
"website": "GeeksForGeeks",
"articles": [
{
"title": "How to access props inside a functional component",
"author": "mathivananshivam",
"published_date": "27-02-2024",
"url": "https://www.geeksforgeeks.org/how-to-access-props-inside-a-functional-component/"
},
{
"title": "Power Spectral Density",
"author": "mathivananshivam",
"published_date": "28-02-2024",
"url": "https://www.geeksforgeeks.org/power-spectral-density/"
},
{
"title": "Why we need Redux in React?",
"author": "mathivananshivam",
"published_date": "14-03-2024",
"url": "https://www.geeksforgeeks.org/why-we-need-redux-in-react/"
}
]
}

Using XMLHttpRequest (XHR)

Using XMLHttpRequest (XHR) involves creating a new instance of XMLHttpRequest, specifying the file URL and request method (typically 'GET'), and setting up event handlers to handle the response asynchronously. This approach allows for direct control over the AJAX request and is suitable for scenarios where a lightweight solution is preferred or when working without additional libraries.

Example: Implementation to show how to load a JSON object from a file with ajax.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>JSON Fetch</title>     <style>         pre {             background-color: #f4f4f4;             border: 1px solid #ddd;             padding: 10px;             overflow-x: auto;             font-family: monospace;             border-radius: 5px;         }     </style> </head>  <body>     <h1>JSON Data</h1>     <div id="json-container">         <!-- Parsed JSON data will be displayed here -->     </div>      <script>         let xhr = new XMLHttpRequest();         xhr.open('GET', 'example.json', true);         xhr.onreadystatechange = function () {             if (xhr.readyState === 4 && xhr.status === 200) {                 let jsonObject =                          JSON.parse(xhr.responseText);                 displayJSON(jsonObject);             }         };         xhr.send();          function displayJSON(jsonObject) {             let jsonContainer =                      document.getElementById('json-container');             let pre =                      document.createElement('pre');             pre.textContent = JSON.stringify(jsonObject, null, 2);             jsonContainer.appendChild(pre);         }     </script> </body>  </html> 

Output:

Screenshot-2024-04-15-151057

Using JQuery

Using jQuery AJAX involves calling the $.ajax() function, specifying the URL and data type (e.g., 'json'), and defining a success callback function to handle the response. This approach abstracts away complexities, providing a simpler syntax and compatibility across different browsers, making it convenient for developers familiar with jQuery.

Example: Implementation to show how to load a JSON object from a file with ajax.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>JSON Fetch Example</title>        <!-- Include jQuery library -->     <script src= "https://code.jquery.com/jquery-3.6.0.min.js">       </script>     <style>         pre {             background-color: #f4f4f4;             border: 1px solid #ddd;             padding: 10px;             overflow-x: auto;             font-family: monospace;             border-radius: 5px;         }     </style> </head>  <body>     <h1>JSON Data</h1>     <div id="json-container">         <!-- Parsed JSON data will be displayed here -->     </div>      <script>         $.getJSON('example.json', function (data) {             displayJSON(data);         });          function displayJSON(jsonObject) {             let jsonContainer =                      document.getElementById('json-container');             let pre = document.createElement('pre');             pre.textContent = JSON.stringify(jsonObject, null, 2);             jsonContainer.appendChild(pre);         }     </script> </body>  </html> 

Output:

Screenshot-2024-04-15-151057



Next Article
How to fetch data from a local JSON file in React Native ?

M

mathivananshivam
Improve
Article Tags :
  • Web Technologies
  • JQuery
  • Node.js
  • Web technologies-HTML and XML
  • JSON

Similar Reads

  • How to Load Data from a File in Next.js?
    Loading Data from files consists of using client-side techniques to read and process files in a Next.js application. In this article, we will explore a practical demonstration of Load Data from a File in Next.js. We will load a validated CSV input file and display its contents in tabular format. App
    3 min read
  • How to post a file from a form with Axios?
    In this article, we are going to discuss making POST requests with form data using the Axios library. Axios is a Promise based HTTP client that can be used for the web as well as for Node.JS development. However, in this article, we are going to strictly refer to client-side use of Axios. To start o
    3 min read
  • How to fetch data from a local JSON file in React Native ?
    Fetching JSON (JavaScript Object Notation) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON data from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access. Implementation: Now let’s start w
    4 min read
  • How to load data from JSON into a Bootstrap Table?
    This article describes how a Bootstrap Table is created using a given JSON  data. The data can be retrieved by either importing it or representing it in JavaScript. The following are given two methods to do it. Displaying JSON data without importing any file: The JSON file that has to be read can be
    4 min read
  • How to Read JSON Files with Pandas?
    JSON (JavaScript Object Notation) store data using key-value pairs. Reading JSON files using Pandas is simple and helpful when you're working with data in .json format. There are mainly three methods to read Json file using Pandas Some of them are: Using pd.read_json() MethodUsing JSON Module and pd
    2 min read
  • How to Import a JSON File to a Django Model?
    In many web development projects, it's common to encounter the need to import data from external sources into a Django application's database. This could be data obtained from APIs, CSV files, or in this case, JSON files. JSON (JavaScript Object Notation) is a popular format for structuring data, an
    4 min read
  • How to work with Node.js and JSON file ?
    Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
    4 min read
  • How to read/write JSON File?
    Ruby is a dynamic, object-oriented programming language developed by Yukihiro Matsumoto in the mid-1990s. Its key features include a simple and elegant syntax, dynamic typing, object-oriented nature, support for mixins and modules, blocks and closures, metaprogramming, and a vibrant community with a
    6 min read
  • How to load data from nested arrays in DataTables ?
    DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for a webpage. It is a very simple-to-use plug-in with a variety of options for the developer’s custom changes as per the application need. The plugin’s features include pagination, sorting, searching,
    4 min read
  • How to read and write JSON file using Node ?
    Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences