Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to Receive JSON Data at the Client Side ?

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 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:

RELATED ARTICLES

Most Popular

Recent Comments