The Wayback Machine - https://web.archive.org/web/20240717024511/https://www.geeksforgeeks.org/how-to-send-data-of-html-form-directly-to-json-file/
Open In App

How to send data of HTML form directly to JSON file?

Last Updated : 01 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

To send HTML form data directly to a JSON file. The process of capturing form inputs, converting them to JSON format, and saving them to a file, ensures efficient data handling and storage

Approach

  • In an HTML form containing several fields such as name, college, etc. We want to send the data of our HTML form directly to the JSON file. We are using the json_encode() function which returns a JSON-encoded string.
  • We are making an array of values that the user fills in the HTML form. Then we pass this array into the json_encode() function. Then, the json_encode() function returns a JSON-encoded string. The whole task is implemented in a PHP function get_data().
  • To create a JSON file we used PHP function file_put_contents(). This function is used to write data to a file. We pass 2 arguments in the file_put_contents() function. The first parameter is our file name in which we want to store data in the JSON format and the second is our get_data() function.
  • This “gfg.php” file demonstrates the PHP code to which the HTML form contents are posted.
  • The content of “gfg.json” file shows the following data in JSON format.

Example: The example below demonstrates the above approach.

html
<html>

<head>
    <meta charset="UTF-8">

    <style>
        h3 {
            text-align: center;
        }

        img {
            display: block;
            margin: auto;
            height: 150px;
            width: 150px;
        }

        .input {
            margin: 6px;
            padding: 10px;
            display: block;
            margin: auto;
            color: palevioletred;
            font-size: 30px;
        }

        input {
            width: 90%;
            display: block;
            margin-left: 12px;
            background: none;
            background-color: lightyellow;
        }

        select {
            width: 90%;
            display: block;
            margin-left: 12px;
            background: none;
            background-color: lightyellow;
        }

        #heading {
            font-family: cursive;
            text-align: center;
            color: green;
            padding-top: 20px;

        }

        #form_page {
            height: 500px;
            width: 50%;
            display: flex;
            flex-wrap: wrap;
            flex-direction: row;
            margin: auto;

        }

        #form_body {
            border-radius: 12px;
            height: 330px;
            width: 450px;
            background-color: beige;
            border: 1px solid pink;
            margin: auto;
            margin-top: 12px;
        }

        #text {
            color: red;
            width: 100px;
        }

        #head {
            border-bottom: 2px solid red;
            height: 100px;
            background-color: aliceblue;
        }

        #submit {
            background-color: white;
            width: 70px;
        }
    </style>

</head>

<body>

    <form method="post" action="gfg.php">

        <div id="form_page">

            <div id="form_body">
                <div id="head">
                    <h1 id="heading">GFG</h1>
                </div>
                <br />
                <div id="input_name" class="input">
                    <input id="name" type="text" 
                        Placeholder="Name" name="name" 
                        required>
                </div>
                <div id="input_class" class="input">
                    <input type="text" placeholder=
                        "Branch" name="branch" required>
                </div>
                <div id="input_year" class="input">
                    <input id="school" type="text" 
                        name="college" 
                        placeholder="College">
                </div>

                <div class="id input">
                    <input id="submit" type="submit" 
                        name="submit" value="submit" 
                        onclick="on_submit()">
                </div>
            </div>
        </div>
    </form>

</body>

</html>
PHP
// gfg.php

<?php
  
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        
        function get_data() {
            $datae = array();
            $datae[] = array(
                'Name' => $_POST['name'],
                'Branch' => $_POST['branch'],
                'College' => $_POST['college'],
            );
            return json_encode($datae);
        }
        
        $name = "gfg";
        $file_name = $name . '.json';
     
        if(file_put_contents(
            "$file_name", get_data())) {
                echo $file_name .' file created';
            }
        else {
            echo 'There is some error';
        }
    }
?>

Output:



Similar Reads

How to Send Email using 'git send-email' via Gmail?
Email communication is a crucial aspect of collaborative software development. Whether you're sharing patches, discussing issues, or coordinating with your team, knowing how to send emails directly from your Git repository can be highly efficient. In this article, we will guide you through the process of configuring and using git send-email with Gm
3 min read
How to append data in JSON file through HTML form using PHP ?
The purpose of this article is to append data to a JSON file through HTML form using PHP. Approach 1: If the JSON file is not created then we create a new JSON file, send data to it, and append data in it. To see how to create a JSON file by taking data from the HTML form, refer this link. Approach 2: If the JSON file is already created then we dir
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
How to Generate or Send JSON Data at the Server Side using Node.js ?
In modern web development, JSON (JavaScript Object Notation) is the most commonly used format for data exchange between a server and a client. Node.js, with its powerful runtime and extensive ecosystem, provides robust tools for generating and sending JSON data on the server side. This guide will walk you through the process of generating and sendi
3 min read
How to take HTML form data as text and send them to html2pdf ?
The html2pdf package is a JavaScript library that enables developers to convert HTML to canvas, PDF, images, and other formats. It accepts HTML as input and adds it to the desired document or PDF. Moreover, it allows users to download the document after adding the HTML content to it. In this tutorial, we will learn how to use the html2pdf npm packa
2 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more. Approach: We are going to fetch JSON data from one of free website,
2 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to send a JSON object to a server using Javascript?
JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we are going to use AJAX (Asynchronous JavaScript And X
2 min read
Difference between res.send() and res.json() in Express.js?
In this article, we will learn about res.send() &amp; res.json(), along with discussing the significant distinction that differentiates between res.send() &amp; res.json(). Let us first understand what is res.send() and res.json() in Express.js? res.send() - The res.send() function is used for sending the response for the HTTP request. It takes a p
3 min read
How to intercept response.send() / response.json() in Express JS
In the context of Express , "intercept" usually refers to the process of capturing or modifying a request or response in a middleware function before it reaches its final destination (e.g., a route handler) or before it is sent back to the client. In Express, intercepting response.send() or response.json() can be achieved by using middleware functi
3 min read
three90RightbarBannerImg