'Saving form submitted data to CSV file using Javascript / JQuery

Trying to submit form data (name and lastname) to a csv file which is stored in the same directory as the html file. Has to be either JavaScript or JQuery because im injecting this into a SquareSpace website which only supports JS.

So far I have been able to serialize the form data into an array which returns

0: {name: "FirstName", value: "John"}
1: {name: "LastName", value: "Doe"}

Spent a couple of hours trying to save this array information into my comments.csv file, to no avail.

Here's the code:

<form id="form">
        Type your first name: <input type="text" name="FirstName" size="20"><br>
        Type your last name: <input type="text" name="LastName" size="20"><br>
        <input type="button" value="submit" id="dl" onclick="clearForm();">
      </form>

    <script>
//Clear form once submitted
function clearForm(){
    document.getElementById("form").reset();
}

$(document).ready(function(){  
    $("button").click(function(){  
        var x = $("form").serializeArray();  
    });                                     
});  

//Submit x array into ./comments.csv file


    </script>

I want to get the firstname and lastname underneath appropriate columns in the csv file. Firstname being 1st column and lastname being 2nd column, in a way that I will be able to display this information in an html table later on.



Solution 1:[1]

You have to parse your form data into CSV format and trigger a link to download. See implementation below

       <form id="form">
          Type your first name: <input type="text" name="FirstName" size="20"><br>
          Type your last name: <input type="text" name="LastName" size="20"><br>
          <input type="button" value="submit" id="dl" onclick="submitForm()">
        </form>

        <script>
          //Clear form once submitted
          function clearForm(){
              document.getElementById("form").reset();
          }

          function submitForm() {
            var formData = $("form").serializeArray();
            let csv = "data:text/csv;charset=utf-8,"; // accept data as CSV

            formData.forEach(function(item) {
              csv += item.value + ";"; // concat form value on csv var and add ; to create columns (you can change to , if want)
            });

            var encodedUri = encodeURI(csv);

            // if you want to download
            var downloadLink = document.createElement("a");
            downloadLink.setAttribute("download", "FILENAME.csv");
            downloadLink.setAttribute("href", encodedUri);
            document.body.appendChild(downloadLink); // Required for FF
            downloadLink.click();
            downloadLink.remove();

            clearForm();
          }
        </script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1