Transform JSON data into a CSV file using JavaScript or C# in an MVC4 framework, then import the data into

I am facing an issue with my website. Currently, when a user submits an application form, an email is sent. However, I would like to create a CSV file containing the form data and then automatically populate my database using this CSV file.

Here is my ASP form:

<div class="submit">
    <div class="left">
        <div class="field"><input id="inputFirstname" type="text" value="First name *" class="watermark" name="firstname"/></div>
        <div class="field"><input id="inputLastname" type="text" value="Last name *" class="watermark" name="lastname"/></div>
        <div class="field"><input id="inputEmail" type="text" value="E-mail *" class="watermark" name="email"/></div>
        <div class="fieldradio" style="margin-bottom:10px;">
                <label class="watermark" style="display:inline">Gender *</label>
                    <input id="inputGenderM"  class="watermark"  style="display:inline;width: 10px" name="gender" type="radio"  />
                <label class="watermark"  style="display:inline">M</label>
                    <input id="inputGenderF"  class="watermark"  style="display:inline;width: 10px"  name="gender" type="radio" />
                <label class="watermark"  style="display:inline">F</label>
        </div>
 </div>
 <div class="right">
    <div class="textarea"><textarea id="inputMessage" name="message" class="watermark">Add your message here</textarea></div>                               
    <div style="float:left;width:100%; margin-top:30px;">
    <div id="captchadiv"><input id="captchaInput" type="text" value="Enter validation text *" name="captchaInput" class="watermark" style="margin-top:10px;"/></div>
   </div>
   <div class="clear"></div>
   <div class="submit_container" id="submitArea">
       <a onclick="javascript:submitCV();" class="btn orange height_19 submit"><span>
        SEND FORM</span></a>
   </div>
</div>

The JavaScript function "submitCV()":

$(document).ready(
    function(){

        $.getJSON('http://jsonip.appspot.com/?callback=?',
    function(data){
      clientIP = data.ip;
    });

 function submitCV() {
    // Validation code
}

function submitSucceeded(result) {
    // Success handling code
}

function submitFailed(error) {
    // Error handling code
}

Is there a quick way to implement creating a CSV file for storage? What do you suggest?

Additionally, I would like to know how to automatically populate an Access database with each new CSV file. Would a Unix script or VB be suitable for this task if the CSV files are stored in an FTP folder?

Answer №1

If you have succeeded in extracting the JSON data from the form, you can employ the following function called JSONTOCSVConverter :

function ConvertJSONToCSV(JSONData, FileName, DisplayLabels) {

       //If JSONData is not an object, then parse it into an Object using JSON.parse
       var dataArray = typeof JSONData !== 'object' ? JSON.parse(JSONData) : JSONData;

       var CSVString = '';
       if (DisplayLabels) {
           var labelRow = "";
           //Extract labels from the first row of the array
           for (var key in dataArray[0]) {
               //Convert values to string and separate them with commas
               labelRow += key + ',';
           }
           labelRow = labelRow.slice(0, -1);

           //Append Label row with a line break
           CSVString += labelRow + '\r\n';
       }

       //Loop through each row
       for (var j = 0; j < dataArray.length; j++) {
           var dataRow = "";
           //Nested loop to extract each column and convert it to a comma-separated string
           for (var key in dataArray[j]) {
               dataRow += '"' + dataArray[j][key] + '",';
           }
           dataRow.slice(0, dataRow.length - 1);
           //Add a line break after each row
           CSVString += dataRow + '\r\n';
       }

       if (CSVString === '') {
           alert('No data available');
           return;
       }

       //Replace blank spaces in the file name with underscores
       var modifiedFileName = FileName.replace(/ /g, "_");

       //Choose file format as csv or xls
       var uriLink = 'data:text/csv;charset=utf-8,' + escape(CSVString);

       //Generate a temporary <a /> tag
       var linkTag = document.createElement("a");
       linkTag.href = uriLink;

       //Set visibility to hidden so it doesn't affect the layout
       linkTag.style = "visibility:hidden";
       linkTag.download = modifiedFileName + ".csv";

       //Append the anchor tag and remove it after automatic click
       document.body.appendChild(linkTag);
       linkTag.click();
       document.body.removeChild(linkTag);
   }

Answer №2

Despite the code already present in my form, I have a question:

<div class="submit_container" id="submitArea">
    <a onclick="javascript:submit();" class="btn orange height_19 submit"><span>
        SEND FORM</span></a>
</div>

Is it possible to include another method within the existing submit function?

Or should I create a separate function for this purpose?

    $(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});

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

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

What is the best way to transfer data from a div tag to an li tag using JavaScript?

https://i.stack.imgur.com/se2qk.pngI am attempting to change the div tag content to li tag. Here is a snippet of the code from inspect for reference. I need to remove the div tag with the "domTitle" class. <li style="display: inline;" id="list_name"> ...

Converting Census Geocoder JSON data into an XML dataset with the help of JSON.net library in C# programming language

In the process of developing a .Net application using Visual Studio 2012, my goal is to query an address table in my SQL database and utilize the Census Geocoding API to obtain the specific MSA for each address. While I have code already set up for the dat ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Placing an object to the right side

I'm currently developing an app using React Native and I need to position something on the right side of the screen. <View style={searchDrop}> <TextInput style={textInput} placeholder="Search Coin ...

Is there a way to automatically update the latest ID in one tab or window when inserting records in a separate tab or window?

I currently have a setup where one file, list-display.php, displays the latest ID. <div class="result"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script> function refresh ...

Tips for storing and retrieving high scores in a JavaScript game

I've just finished creating a JavaScript snake game and now I'd like to add a "scores" option that displays the top 10 players along with their names and scores. My initial plan was to create an object containing the player's name and score ...

Creating an animated transition for an element's height with CSS

I need to animate the height of a div that doesn't have a specified height. Using max-height isn't an option due to multiple potential height amounts. I attempted adding transition: height 0.2s ease to the div, but it didn't work as expecte ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

Error in scrolling previews detected in Jssor horizontal template maker

I've been working with Jssor Slider Maker and I'm using the vertical preview template that features two columns on the left side and a maximized image on the right side. After pulling the code from the developers pack, it includes scripts, CSS an ...

Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the s ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

What could be the reason for the failure of @babel/preset-react automatic transformation with Webpack?

The setup involves a Yarn monorepo with a babel.config.js that specifies the environment. React version being used is 18.1.x. I have a similar configuration that works perfectly fine in another setup, but it's failing here. I've been painstaking ...

Implementing AsyncTask in Android to establish a connection with MySQL database through PHP

Looking for assistance on implementing this with AsyncTask? You can check out this tutorial: . Having trouble getting it to work on android 4.0.3. Any help would be greatly appreciated. Thank you in advance. ...

Issues are arising with Jquery Scripts when running through Selenium in IE 9, resulting in the error message SCRIPT5009: '$' is undefined. However, these scripts are functioning correctly when executed directly in the web browser

While using Selenium, the code below is causing issues as it is not functioning properly. An error SCRIPT5009: '$' is undefined is being thrown in IE 9. However, if the code is executed in a web browser console after removing the "\" sign, i ...

What methods can I utilize to modify nested fields in a Logic App?

Situation: I am eager to update nested fields using the LogicApp Steps taken: Executed the query to retrieve the necessary documents Established a global variable to store the array intended for 'updating' Iterated through the initial q ...

Verify the Existence of a Key in JSON Array

I am attempting to create a validation check to determine the presence of a specific key within a JSON array using jQuery. If this key is found, it indicates that no relevant objects were returned from the server and therefore nothing should be displayed o ...

What is the reason for IE displaying null when the model does not exist?

Why does IE 11 render 'null' if my model does not exist? For instance: <tr> <td [innerHTML]="model?.prop1 | my-pipe"></td> </tr> Imagine this scenario: When the page loads, a request is sent to the server and the res ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...