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

How to Receive JSON Data at the Client Side ?

Last Updated : 10 Mar, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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 example will demonstrate this approach.

Frontend Portion: The HTML code consists of a form having two inputs (name and email), one send button to send data to the server, and one empty paragraph tag to display the response of the server. A string must be used to send data to a web server. As a consequence, we change data into a string and send it to the server via an XHR request using the JSON.stringify() function.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color: green">Welcome to GFG</h1>
    <input type="text" id="name"
           placeholder="Your name" />
    <input type="email" id="email"
           placeholder="Email" />
    <button onclick="sendJSONdata()">Send</button>
    <p id="result" style="color: blue"></p>
  
    <script>
        function sendJSONdata() {
            var name = 
                document.getElementById("name").value;
            var email = 
                document.getElementById("email").value;
            var result = 
                document.getElementById("result");
  
            // Creating a XHR object
            var xhr = new XMLHttpRequest();
  
            // open a connection
            xhr.open("POST", "/userdata");
  
            // Set the request header
            xhr.setRequestHeader(
              "Content-Type", "application/json"
            );
  
            // Converting JSON data to string
            var data = JSON.stringify(
              { name: name, email: email }
            );
            xhr.send(data);
  
            // Create a state change callback
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 &&
                    xhr.status === 200) {
                    // Print received data from server
                    result.innerHTML = this.responseText;
                }
            };
        }
    </script>
</body>
  
</html>


Backend Portion: We have used the express framework of NodeJS to create the server which is running on port 3000.

Javascript




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("/userdata", function (req, res) {
    res.send(
        `Hello ${req.body.name}, your email is ${req.body.email}`
    );
});
  
app.listen(3000, function () {
    console.log("Server started on port 3000");
});


Output:



Similar Reads

How to Receive JSON Data at Server Side ?
JavaScript Object Notation (JSON) is a data transferring format used to send data to or from the server. It is commonly utilized in API integration due to its benefits and simplicity. In this example, we will utilize XML HttpRequest to deliver data to the server. Frontend: We will use a simple form containing name and email as an input and submit b
2 min read
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 Generate/Send JSON Data at the Client Side ?
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
3 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 receive JSON POST with PHP ?
In this article, we will see how to retrieve the JSON POST with PHP, &amp; will also see their implementation through the examples. First, we will look for the below 3 features: php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless
2 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
three90RightbarBannerImg