1

I have no experience working with ajax . I am stuck with a problem where i want a button to post form data to url (API) which gives json response as :

{  
    "employee": {  
        "name":       "sonoo",   
        "salary":      56000,   
        "married":    true  
       }  
   } 

Now pressing submit button should give an option to download above json resposne to excel ? Can anybody please help or guide me what should i learn to solve this ?

Paras Ghai
  • 333
  • 2
  • 12

2 Answers2

1

If you already have the JSON code, you can read this answer: How to download JSON object as a file - StackOverflow.

And if you need to convert it to a CSV file, you can use this to manually convert it: JSON to CSV Converter.

If you really need the JSON code to be converted to CSV with JavaScript, I think this answer will help: How to convert JSON to CSV with JavaScript.

Faris Han
  • 192
  • 12
1

First, you will need to learn how to send requests and receive responses using AJAX. When you know how to receive an AJAX response properly you can do the following to download the JSON response as an Excel file:

  • You can use Blob and URL.createObjectURL() to create a link to download the response as a file.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
 function download(){
    var jsonResponse = '{ "employee": { "name": "sonoo", "salary": 56000, "married": true } }' ;
    
    if (confirm('Download response to Excel file?')) {
    var fileName = "";
    var columnNames = [];
    var records = [];
    var responseExcel = "";
    var jsObject = JSON.parse( jsonResponse );

   for (var key in jsObject) {
    fileName = key + ".csv";
    if (jsObject.hasOwnProperty(key)) {
     for (var key2 in jsObject[key]) {
      columnNames.push(key2);
      if (jsObject[key].hasOwnProperty(key2)) {
       records.push(jsObject[key][key2]);
      }
     }
    }
   }
   
   responseExcel = columnNames.join(";") + "\n";
   responseExcel += records.join(";");
   
   var blob = new Blob([responseExcel], {type: "text/plain"});
   var url  = URL.createObjectURL(blob);

   var a = document.createElement('a');
   a.href        = url;
   a.download    = fileName;
   a.textContent = "Download " + fileName;

   document.getElementById('json').appendChild(a);
  } else {
   // Do something else ...
  }
 }
  </script>
</head>
<body>

<h1>My Page</h1>
<p>Some paragraph.</p>

<button onclick="download();">Submit</button><br><br>
<div id="json"></div>

</body>
</html>