Last active
March 30, 2021 11:08
-
-
Save lshaf/8cddddb14d72537a106444cf3d978506 to your computer and use it in GitHub Desktop.
send POST with form using JSON data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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