The Wayback Machine - https://web.archive.org/web/20240529040038/https://www.geeksforgeeks.org/how-to-generate-send-json-data-at-the-client-side/
Open In App

How to Generate/Send JSON Data at the Client Side ?

Last Updated : 25 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Javascript Object Notation (JSON) is a widely used format for sending and receiving data to or from the server. In this article, we will use fetch API to send and receive data from the NodeJS server. 

Advantages of JSON:

  • Because of its easy and small syntax, it executes the response in a faster way.
  • It is supported by a wide range of browsers.
  • Parsing at the server-side using JSON is very fast.
  • It is the most suitable format for transferring data of any size. This is due to the fact that JSON stores data in arrays, which makes it easier to transmit.

Why use Fetch API?

  • The Fetch API is a modern method that allows web browsers to send HTTP requests to servers.
  • It is similar to XMLHttpRequest but a lot simpler and clearer.
  • It makes use of Javascript Promises to give more customizable choices for making server requests from web browsers.

Setup and Installation

Step 1: Create a folder named SendDataToClient and run the following command to initiate a NodeJS application.

npm init -y 

Step 2: Install the necessary npm packages using the following command.

npm install express body-parser

Step 3: Create index.html and server.js in your Project directory. 

Project Structure: Now, our project directory will look like this.

Frontend Code: The structure is straightforward, with two inputs: one for name and one for email. A send button to send the input data to the server and an empty paragraph to display the server’s JSON response. 

index.html




<!DOCTYPE html>
<html>
<head>
<title>Send data to client</title>
<script>
    function sendData() {
        var name = document.getElementById("name").value;
        var email = document.getElementById("email").value;
        var result = document.getElementById("result");
        
        fetch("/jsondata", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ name: name, email: email }),
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (data) {
            result.innerHTML = data.msg;
          })
          .catch(function (error) {
            console.log(error);
          });
    }
</script>
</head>
<body>
    <h1 style="color: green">GFG</h1>
    <input type="text" id="name" placeholder="Your name" />
    <input type="email" id="email" placeholder="Email" />
    <button onclick="sendData()">Send</button>
    <p id="result" style="color: orange"></p>
  
</body>
</html>


Backend Code: The Express framework with NodeJS is used to build the server, which runs on port 3000. Whenever the user clicks on send button it sends a POST request containing JSON data on /jsondata route and then the server responded with a JSON reply.

server.js




const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.json());
  
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});
  
app.post("/jsondata", function (req, res) {
    res.json({ msg: `Hello ${req.body.name}, your email is ${req.body.email}` });
});
  
app.listen(3000, function () {
    console.log("Server started on port 3000");
});


Steps to Run the Application: To run the application using the following command:

node server.js

Output: Go to http://localhost:3000/ to see the output screen.



Similar Reads

Server Side Rendering vs Client Side Rendering vs Server Side Generation
In the world of web development, there are several approaches to rendering web pages: server-side rendering, client-side rendering, and server-side generation. Each approach has its own advantages and disadvantages, and choosing the right one for your project depends on your specific needs and goals. In this blog, we’ll explore the differences betw
4 min read
How to Receive JSON Data at the Client Side ?
For sending and receiving data to or from the server JSON format is used. JSON stands for Javascript Object Notation and it is a widely used format nowadays because of its advantages and simplicity. In this article, we will use XML HttpRequest to receive data from the server and use NodeJS for the backend for sending JSON data. Example: The below e
2 min read
Difference between Server-Side AJAX framework and Client-side AJAX framework ?
The article focuses on discussing the differences between the Server-side AJAX framework and the Client-side AJAX framework. The following topics will be discussed here: What is a Server-side AJAX framework?What is a Client-side AJAX framework?Server-side AJAX framework vs Client-side AJAX framework Let's start discussing each of these topics in de
3 min read
Server side and Client side Programming
Server-side Programming : It is the program that runs on server dealing with the generation of content of web page. 1) Querying the database 2) Operations over databases 3) Access/Write a file on server. 4) Interact with other servers. 5) Structure web applications. 6) Process user input. For example if user input is a text in search box, run a sea
2 min read
How does SSR(Server-Side Rendering) differ from CSR(client-side rendering) ?
Server-Side Rendering (SSR) and Client-Side Rendering (CSR) are two different approaches used in web development to render web pages to users. Each approach has its own set of advantages and disadvantages. In this article, we will learn about the difference between SSR and CSR with examples and features. Table of Content Server-Side Rendering (SSR)
4 min read
How to send data from client side to Node.js server using Ajax without page reloading ?
In this article, we are learning about how can we send data to a node server using Ajax without reloading the page from the client-side. Approach: We are creating a button in HTML document on the client-side when the button is pressed a request is made on our node server and the object is received at our server without reloading the page. This can
2 min read
How to define a client-side script in HTML5 ?
To define a client-side script in HTML5, we can do &lt;script&gt; tag or adding external script file by src attribute to the HTML file. &lt;script&gt; tag contains the JavaScript to be added for the client-side scripting. Syntax: &lt;script&gt; // JavaScript goes here console.log('GeeksforGeeks'); &lt;/script&gt; Below are the examples for the abov
1 min read
How to create a client-side image-map in HTML5 ?
In this article, we will create a client-side image map by using an &lt;img&gt; tag. The &lt;img&gt; tag is used to add images on a webpage. This tag is an empty tag which means it can contain only a list of attributes and it has no closing tag. Syntax: &lt;img src="url" alt="some_text" usemap="#mapname"&gt; Example: &lt;!DOCTYPE html&gt; &lt;html
1 min read
What is Client-Side Filter Bypass?
Many websites lack client-side filter checks, so it becomes easy to bypass that. But, our bypass will only be successful if there is no server-side filter check either. First, let's dig a little bit about the client-side filter bypass. Client-Side FilterThese filters ensure that the input given by the user is in the correct format. Basically, this
2 min read
How to set alternate content for users that do not support client-side scripts ?
In this article, we define an alternate content for users that do not support client-side scripts by using &lt;noscript&gt; tag in the HTML document. It is used to display the text for those browsers that does not support script tag or the browsers disable the script for the user. Syntax: &lt;noscript&gt; Contents... &lt;/noscript&gt; Example: &lt;
1 min read