Skip to content

Instantly share code, notes, and snippets.

@lshaf
Last active March 30, 2021 11:08
Show Gist options
  • Save lshaf/8cddddb14d72537a106444cf3d978506 to your computer and use it in GitHub Desktop.
Save lshaf/8cddddb14d72537a106444cf3d978506 to your computer and use it in GitHub Desktop.
send POST with form using JSON data
function formPost(url, data, callback) {
let form = $("<form>", {
method: 'POST',
action: url,
target: "_blank"
});
function generateInput(iData, namePrefix) {
if (namePrefix === undefined) namePrefix = "";
for ([keyData, vData] of Object.entries(iData)) {
let nameInput = keyData;
if (namePrefix !== "") nameInput = `${namePrefix}[${keyData}]`
if (typeof vData === "object") {
if (vData.hasOwnProperty('length')) {
for ([idxData, aData] of Object.entries(vData)) {
if (typeof aData === 'object') {
generateInput(aData, `${nameInput}[${idxData}]`);
} else {
let inp = $("<input>", {
type: 'hidden',
name: nameInput,
value: vData
});
inp.appendTo(form);
}
}
} else {
generateInput(vData, nameInput)
}
} else {
let inp = $("<input>", {
type: 'hidden',
name: nameInput,
value: vData
});
inp.appendTo(form);
}
}
}
generateInput(data);
form.appendTo($('body'));
form.submit();
form.remove();
if (typeof callback === "function") {
callback();
}
}
// usage
formPost("https://domain.com/download/post", {
query: "Hello",
filter: {
class_id: 10,
unique: 1
},
order: [
{dir: 'asc', column: 1}
]
}, function() {
alert("Complete");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment