1

Let's say I have an HTML document with forms and inputs and a submit button.

What I want to happen is, every time the user clicks that submit button, it will generate a JSON file with the form data, without using Node.js or a server.

I'm sorry if this is a dumb question; this is just an assignment given to me by my instructor. Basically, what I have is an HTML file with an embedded script. It's like an online shop concept with the user credentials to input on the form and then generate a JSON file with that data.

Pang
  • 9,564
  • 146
  • 81
  • 122
ronjou
  • 21
  • 1
  • 4

1 Answers1

1

Everyone seems to be forgetting about the blob Object. Here's an example. It might be weird because of how stack overflow's demo tool works. I hope this helps!

Edit:

Based on the comment I realized it wasn't SO, but my code. You simply change the type of blob from application/json to octet/stream and add a download attribute (note: this is html5) and tah dah! it works.

function convertToJSON() {
  var firstname = document.getElementById('firstname').value;
  var lastname = document.getElementById('lastname').value;
  var email = document.getElementById('email').value;

  var jsonObject = {
    "FirstName": firstname,
    "LastName": lastname,
    "email": email
  }

  document.getElementById('output').value = JSON.stringify(jsonObject)
}

function saveToFile() {
  convertToJSON();
  var jsonObjectAsString = document.getElementById('output').value;

  var blob = new Blob([jsonObjectAsString], {
    //type: 'application/json'
    type: 'octet/stream'
  });
  console.log(blob);

  var anchor = document.createElement('a')
  anchor.download = "user.json";
  anchor.href = window.URL.createObjectURL(blob);
  anchor.innerHTML = "download"
  anchor.click();

  console.log(anchor);

  document.getElementById('output').append(anchor)


}
<br>First Name: <input id="firstname" value="John">
<br>Last Name:<input id="lastname" value="Pavek">
<br>Email:<input id="email" value="Example@example.com">
<br>
<button onclick="convertToJSON()">Convert</button>
<button onclick="saveToFile()">Save</button>
<hr> output: <br>
<textarea id="output"></textarea>
Community
  • 1
  • 1
John Pavek
  • 2,595
  • 3
  • 15
  • 33
  • Sorry but when I click "Save" it just opens something like "blob:null/15f0f9f0-b1aa-44d7-b2d8-b3cab1ad8b9b" with the stringified json but without the "download" anchor. I also tried right clicking to save file but the "Save as.." is grayed. I'm using chrome. Thank you! – ronjou Jan 11 '18 at 22:07
  • @ronjou I've updated my answer, I hope that is what you're looking for! – John Pavek Jan 13 '18 at 03:57
  • I ended up using localStorage api but your code is exactly what I was looking for! I really appreciate your answer, thank you very much ! – ronjou Jan 15 '18 at 00:52