JSFiddle - React, Tailwind, and code Playground

by asif097

HTML

<!-- soource http://stackoverflow.com/questions/28120177/save-json-file-locally -->
<input id="filename" type="text" placeholder="Please enter filename" />
<button for="filename">click</button><a id="download" download="" href=""></a>

<br />
<div class="shape"></div>

CSS

/\n/g

JavaScript

var jsonData = {
    "2015": [{
        "color": "rgb(0, 128, 0)",
            "width": "50px",
            "height": "50px"
    }]
};

$(function () {
    $("[for=filename]").on("click", function (e) {
        var shape = $('.shape');
        var name = $("#filename").val() || "data-" + $.now();

        shape.data('holidays', jsonData);
        
        $('.shape').text(jsonData);
        
        var request = function (url, filename) {
            var file = {
                json: JSON.stringify(shape.data('holidays'))
            };
            return $.ajax({
                beforeSend: function (jqxhr, settings) {
                    jqxhr.filename = filename;
                },
                url: url,
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: file
            }).then(function (data, textStatus, jqxhr) {
                $("a#download").attr({
                    "download": jqxhr.filename + ".json",
                        "href": "data:application/json;charset=utf8;base64," + window.btoa(JSON.stringify(data))
                }).get(0).click();
            }, function (jqxhr, textStatus, errorThrown) {
                console.log(textStatus, errorThrown)
            });
        };
        request("/echo/json/", name)
    });
})