Efficiently incorporate a set of fields into a form and automatically produce JSON when submitted

The optimal approach for dynamically adding a set of fields and generating JSON based on key-value pairs upon form submission.

<div class="container">
  <div class="col-md-4">
    <form method="POST" id="myform">
      <div class="form-group">
        <label for="title">Past Question Title</label>
        <input type="text" class="form-control" id="pqtitle" name="pqtitle" placeholder="Type Question Here" cols="40" rows="5" style="resize:vertical;" required>
      </div>
      <div class="form-group">
        <label for="course">Course Code</label>
        <select type="text" class="form-control" id="coursecode" name="coursecode" placeholder="Course"></select>
        <option></option>
      </div>
      <div id="fielda">
        <div id="fielda0">
          <!-- Text input-->
          <hr/>
          <fieldset>
            <legend>Question 1</legend>
            <div class="form-group">
              <label for="question1">Question</label>
              <textarea type="text" class="form-control" id="question1" name="question1" placeholder="Type Question Here" cols="40" rows="5" style="resize:vertical;" required></textarea>
            </div>
            <div class="form-group">
              <label for="nt">Upload Image</label>
              <input type="file" name="file" class="filestyle" data-iconName="glyphicon glyphicon-inbox">
            </div>
            <div class="form-group">
              <label for="options">Options</label>
              <div data-role="dynamic-fields">
                <div class="form-inline">
                  <div class="form-group">
                    <div class="col-md-12">
                      <input type="radio" name="answer1" id="answer1" value="Answer">Answer
                      <span>-</span>
                      <label class="sr-only" for="option1">Option</label>
                      <input type="text" class="form-control" id="option1" name="option1" placeholder="Type Option Here">
                    </div>
                  </div>
                  <button class="btn btn-danger" data-role="remove">
                    <span class="glyphicon glyphicon-remove"></span>
                  </button>
                  <button class="btn btn-primary" data-role="add">
                    <span class="glyphicon glyphicon-plus"></span>
                  </button>
                </div>
                <!-- /div.form-inline -->
              </div>
              <!-- /div[data-role="dynamic-fields"] -->
            </div>
            <div class="form-group">
              <label for="slug1">Slug</label>
              <textarea type="text" class="form-control" id="slug1" name="slug1" placeholder="Explain Your Answer" cols="40" rows="5" style="resize:vertical;" required></textarea>
            </div>
            <div class="form-group">
              <label for="point1">Point</label>
              <input type="number" class="form-control" id="point1" name="point1" placeholder="Allocate Score Here" required>
              <hr/>
            </div>
          </fieldset>
        </div>
        <!--end field0-->
      </div>
      <!--end field-->

      <div class="form-group">
        <div class="col-dm-2 text-right">
          <button id="add-more" name="add-more" class="btn btn-primary">Add More</button>
          <button type="submit" class="btn btn-danger" name="submit">Submit</button>
        </div>
      </div>

    </form>
  </div>
</div>

Answer №1

I completely agree with @MagikalWizard's suggestion to construct your JSON data using field-value pairs. Once you have the complete JSON array object, the next step would be to initiate an ajax POST request to send the array to a server-side PHP page:

$.ajax({
    type: 'POST',
    url: 'save_json_file.php',
    data: {'myjsondata': your_json_array},
    success: function(msg) {
      //alert(msg);  // You can display the response from the POST request here for confirmation of completion/success.
    }
});

Subsequently, in PHP, you can retrieve the posted JSON data and save it to the server using file_put_contents:

$data_to_save = json_decode(file_get_contents('php://input'), true);
file_put_contents($data_to_save, 'newfilesaved.json');

Note: It might be necessary to encode the inbound JSON data.

Additionally, you can obtain form data as JSON by utilizing:

$('form').serializeArray()

You can refer to this example I quickly put together on JSFiddle.

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

Please proceed by submitting all radio buttons that have been checked

Seeking assistance with creating a quiz application using the MEAN stack. Once all questions are attempted, there will be a submit button for checking all selected radio buttons - option 1 corresponds to 1, option 2 to 2, and so on. The current structure o ...

Converting JSON data into rows within a Postgres stored procedure: A step-by-step guide

Currently, I am faced with the challenge of creating a stored procedure in Postgres. The data that I have in Postgres is structured as JSON, as shown below. { "identifiers": [ { "identifierType": ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Ways to convert a JSON file into a ListView using Volley

I'm currently developing an app that requires fetching data from the internet, such as names and email addresses. I followed tutorials on using Volley to parse a JSON file and successfully retrieved the data. However, I encountered an issue when tryin ...

Retrieving data from an array using an AJAX request function

I've been attempting to utilize an AJAX call to update a series of image elements on a webpage. The array containing the elements to update is populated with URLs fetched from a PHP page via AJAX. The issue I'm encountering with the code provide ...

Issue in Wordpress: ReferenceError - '$' is not defined

Currently utilizing WordPress and attempting to access the following code snippet. I am encountering an error on the last line }(jQuery)); (function($) { $(function () { // Slideshow 3 $("#slider3").responsiveSlides({ auto: true, pag ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

Technique for updating URL when submitting a form on a webpage

I'm a newcomer to the world of coding and I have a simple issue that needs fixing. I want to create a form field where users can input the last segment of a URL provided to them. After entering this segment, I want the page to refresh automatically a ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

Tips for creating a curved shape using fabric.js

I am encountering an issue while trying to draw an arc using a circle with a start and end angle in my code. Here is the snippet I am working with: var circle = new fabric.Circle({ radius: 30, left: 20, top: 20, fill: " ...

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

Learn the process of dynamically wrapping component content with HTML tags in Vue.js

Hey there! I'm looking to enclose the content of a component with a specific HTML tag, let's say button for this scenario. I have a function that dynamically returns a value which I use as a prop. Based on that, I want to wrap the component&apos ...

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...

Even after implementing a setTimeout function, both Promises and Axios requests are still resulting in a

Recently, I've encountered an issue with the Reverse Geocode API from TomTom. The problem arises when I send multiple latitude and longitude coordinates (around 72 of them) to the API, resulting in frequent 429 responses. To address this issue, I att ...

Decoding JSON information received from Unity and passing it to Ruby on Rails

Currently, I am in the process of developing a Rails service to support a Unity front end. One of my controllers seems to be encountering an issue when trying to parse the JSON blob received from my UnityWebRequest. Unity claims it is sending the following ...

What's the best way to create multiple lines within a post body using Postman?

How can I include line breaks in a JSON request body using Postman? I need to submit the following raw (application/json) body in a POST request: {"csrRequest":"-----BEGIN CERTIFICATE REQUEST----- MIICwzCCAasCAQAwfjELMAkGA1UEBhMCc3YxEjAQBgNVBAgMCVN 0b2Nra ...

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

Confusion arises when Java encounters an out-of-bounds index while dealing

Imagine you have a String temp = "efgh"; System.out.println(temp.substring(0,4)); // out of range, no exception System.out.println(temp.substring(0,5)); // out of range, exception thrown What causes this discrepancy? ...

Implementing Date.now() as a Schema Field Type in Meteor's Simple-Schema

Within my Meteor application, I have utilized Date.now() to generate a timestamp for inclusion in a new MongoDB document. Although Date.now() appears to be an appropriate choice for my app, I lack expertise in managing dates and times. As I transition to ...