Convert HTML form input into a JSON file for safekeeping

<div class="email">
<section class="subscribe">
<div class="subscribe-pitch">
</div>
<form action="#" method="post" class="subscribe-form" id="emails_form">
<input type="email" class="subscribe-input" placeholder="Enter email for newsletter" >
<button id="email_submit" type="submit" value="send" class="subscribe-submit"><i class="fa fa-chevron-right"></i></button>
</form>

I am seeking assistance in saving input data from a basic email form to a JSON file. I believe this can be accomplished using JavaScript. Could someone kindly provide a step-by-step guide as I am new to this?

Answer №1

VIEW DEMO

Utilizing the process of serializing, we are able to store input from an HTML form into JSON output.

<script type="text/javascript>
  $(document).ready(function() {
  $("#submitBtn").click(function(e){
     var jsonData = {};

   var formData = $("#myForm").serializeArray();
  
   $.each(formData, function() {
        if (jsonData[this.name]) {
           if (!jsonData[this.name].push) {
               jsonData[this.name] = [jsonData[this.name]];
           }
           jsonData[this.name].push(this.value || '');
       } else {
           jsonData[this.name] = this.value || '';
       }


   });
   console.log(jsonData);
    $.ajax(
    {
        url : "process.php",
        type: "POST",
        data : jsonData,

    });
    e.preventDefault(); 
});
});
</script>

HTML CODE

<div id="header">
 Sending Form Data as JSON
</div>

<form id="myForm" type="post">
  <fieldset>
    <legend>Ajax Form Submission </legend>
    <p>Share your feedback with us by filling out the form below</p>
    <div class="elements">
      <label for="name">Name :</label>
      <input  required="required" type="text"  value="John Doe" name="fname"  size="20"  />
    </div>
     <div class="elements">
      <label for="Age">Age :</label>
      <input required="required" type="number" value="25" id="age" name="age" size="10" />
    </div>  
    <div class="elements">
      <label for="pro"> Profession :</label>
      <select name="pro">
   <option value="Student">Student</option>
   <option value="Engineer" selected="selected">Engineer</option>
   </select>
    </div>      
    <div class="elements">
    <label for="Gender">Gender: </label>
      <input type="radio" name="gender" value="Male" checked="checked" id="r1"> Male 
  <input type="radio" name="gender" value="Female" id="r2"> Female 
</div>  
    <div class="elements">
      <label for="hobby">Hobby :</label>
      <input type="checkbox" name="hobby[]" value="Music" id="ch1" checked="checked"> Music 
  <input type="checkbox" name="hobby[]" value="Reading"  id="ch2"> Reading 
   </div>

    <div class="submit">
       <input type="submit" id="submitBtn" name="submitBtn" class="btn" value="Submit" />
    </div>
    <span class="elements">Press "Ctrl + Shift + J" to view sent JSON in console: <span>
  </fieldset>
</form>

Answer №2

To successfully write data to a JSON file using Node.js, you should follow these steps:

'use strict';

const fs = require('fs');

let student = {
    name: 'Mike',
    age: 25,
    gender: 'Male',
    department: 'English',
    car: 'Honda'
};

let jsonData = JSON.stringify(student);

fs.writeFileSync('file.json', jsonData, callback);

function callback(err) {
    if (err) {
        console.log('Error writing file');
    } else {
        console.log('Data written successfully');
    }
}

Answer №3

Using jQuery makes it really easy:

const jsonData = JSON.stringify($("#contact_form").serializeArray());

If you wish to save the jsonData in a JSON file, you will need to send it to the server (e.g. via AJAX) and store it there. Alternatively, you can directly send the form data to the server and convert it into JSON on the server side.

Take a look at this detailed explanation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use cookies to make an HTML div disappear when a button is clicked?

I've been attempting to conceal this message in Vue.js, but so far I haven't had any luck. Currently, I am utilizing the js-cookie library. My objective is as follows: HTML <div v-show="closeBox()"> < ...

Use jQuery to set a Firebase image as the background of a div element

Is there a way to fetch an image from Firebase and use it as the background for a div element? I've tried several approaches without success. Could someone share some examples on how to achieve this? <div class="museBGSize rounded-corners grpelem" ...

I am having trouble scrolling through the main content when the side-drawer is open. How can I fix this issue?

When the sidebar is opened, I am facing issues with the main content scroll and certain fields such as select options and search bar not functioning properly. I have included the main content in the routes from which it is being loaded. However, the scroll ...

Opening the Gmail app from a link using JavaScript

What is the best way to open the Gmail app from a hyperlink? This link opens WhatsApp <a href="https://wa.me/">whatsapp</a> <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f ...

Cross-reference each checkbox value with the corresponding input text ID. If the checkbox is checked, update the value of the input text with the

Is there a way to compare the values of multiple checkboxes in jQuery (with the same name and variable value) to the values of many input text fields (also with the same name and variable value)? And if a checkbox is checked, can we change the value of the ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

What situations warrant the use of unescaped !{} in pug for string interpolation?

Is there a practical application for utilizing !{} - string interpolation in an unescaped format, despite the potential risks associated with its use? I have reviewed the information provided at these sources: Using !{ } and #{ } interpolation in a jade ...

Looking to update to the most recent jscrollpane.js version compatible with jQuery 1.7.1 or 2?

I am facing issues accessing GitHub due to security settings. Can someone please share the most recent version of jscrollpane.js that is compatible with jQuery versions 1.7.1 or 2? ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...

Tips for creating an indent in a new line

https://i.stack.imgur.com/O8Xbv.png I've been trying to figure out how to make the text indent on each new line when it's pushed to a new line due to screen resizing. I've tried using 'display:block' but it doesn't seem to wo ...

Using the OR operator in a JSON server

One way to retrieve data from a json-server (simulated server) is by using the following call: http://localhost:3000/posts?title_like=head&comments_like=today When this call is made, records will be returned where the title is similar to "head" AND c ...

Expo is having trouble locating the module "color-convert" - such a frustrating problem

Having an issue! I ran the command npm start in my terminal and received the following error: Starting project at /home/pc/Documents/Projects/Mobile/weather_app Developer tools running on http://localhost:19002 Cannot find module 'color-convert' ...

JSON format shows Grails nullable column returning a value of {"class":"java.lang.Character"}

I am facing an issue with parsing a JSON object from my legacy database. The column 'customersMname' is defined in the domain's static constraints as: customersMname nullable: true, maxSize: 1 When the field is null, I am getting the follo ...

Retrieve a compilation of Whole Foods locations through the use of rvest

I want to retrieve a list of Whole Foods stores using the rvest package. I've successfully extracted information from various sources like Wikipedia, FIFA, and Yahoo! Finance using this method. However, in this case, the table spans multiple pages but ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someo ...

Avoid repeating media queries in MUI JSS by combining them efficiently

Is there a more efficient way to apply the same set of CSS styles to multiple media query rules without repetition? Currently, the only workaround seems to be: [theme.breakpoints.up('xl')]: { color: 'red', backgroundColor: 'gre ...

After performing an action with Redux, the error message ""Cannot access properties of 'undefined'" is displayed

I am currently developing a Shopping List App using React/Redux. I am facing issues with removing items from a list. When I trigger the 'removeItem' action, the page no longer recognizes the object that represents the list (which was originally s ...

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

PHP - Removing information through button clicks

I've been working on creating an HTML table that displays all the rows from a database table, with a button next to each row for deleting that entry. While I've managed to set up the table, I'm struggling to get the delete buttons to functio ...