- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Send and Receive JSON Data to and from the Server
JavaScript can send network requests to the server and load JSON. JS does this using something called AJAX. AJAX stands for Asynchronous JavaScript and XML. JS has an API, fetch, to GET(receive) and POST(send) information to the server.
You can use fetch to GET JSON data in the following way −
Example
const URL = 'https://jsonplaceholder.typicode.com/todos/1' // Send a GET request without any data to the server fetch(URL, {method: "GET"}) // Get the JSON data from the raw response .then(res => res.json()) // Print the result .then(console.log)
Output
This will give the output −
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
You can also POST data to the server using fetch. For example, to create a new todo on the above server, you can post your own data −
Example
const URL = 'https://jsonplaceholder.typicode.com/todos' const data = { "userId": 1, "title": "delectus aut autem", "completed": false }; // Send a post request fetch(URL, { method: "POST", body: JSON.stringify(data), headers: { "Content-type": "application/json; charset=UTF-8" } })
This will create a todo on the placeholder API.
- Related Articles
- How to retrieve data from JSON file using jQuery and Ajax?
- send(), sendStatus() and json() method in Node.js
- How to send data from one Fragment to another Fragment in Android?
- How to communicate JSON data between C++ and Node.js ?
- How to read data from JSON array using JavaScript?
- How to take HTML form data as text and send them to html2pdf?
- How to send data from one activity to another in Android using intent?
- How to send data from one activity to another in Android using bundle?
- How to send data from one activity to another in Android without intent?
- How to load data from a server in React Native?
- How to read/retrieve data from Database to JSON using JDBC?
- Send data from one Fragment to another using Kotlin?
- How do you receive server-sent event notifications in JavaScript?
- Connecting to and Disconnecting from the MySQL Server
- Data Replication from SAP PO to SQL Server

Advertisements