JSFiddle - React, Tailwind, and code Playground
by rajeshpillai
HTML
<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
#download {
display:none;
}
.shape {
color:green;
width:50px;
height:50px;
}
JavaScript
$(function () {
$("[for=filename]").on("click", function (e) {
var shape = $(".shape"),
name = $("#filename").val() || "data-" + $.now();
shape.data("style", shape.css(["color", "width", "height"]));
var request = function (url, filename) {
var file = {
json: JSON.stringify(shape.data("style"))
};
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)
});
})