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

How to Receive JSON Data at the Client Side ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
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:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Last Updated : 10 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials