Skip to content

Instantly share code, notes, and snippets.

@RyadPasha
Last active March 3, 2021 13:47
Show Gist options
  • Save RyadPasha/63b834cc057855d9e49f46b09129c2c4 to your computer and use it in GitHub Desktop.
Save RyadPasha/63b834cc057855d9e49f46b09129c2c4 to your computer and use it in GitHub Desktop.
/**
* sends a request to the specified url from a form. this will change the window location.
* @param {string} path the path to send the post request to
* @param {object} params the paramiters to add to the url
* @param {string} [method=post] the method to use on the form
*/
function post(path, params, method='POST') {
var form = $('<form></form>');
form.attr("method", method);
form.attr("action", path);
$.each(params, function(key, value) {
if ( typeof value == 'object' || typeof value == 'array' ){
$.each(value, function(subkey, subvalue) {
var field = $('<input />');
field.attr("type", "hidden");
field.attr("name", key+'[]');
field.attr("value", subvalue);
form.append(field);
});
} else {
var field = $('<input />');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
}
});
// The form needs to be a part of the document in
// order for us to be able to submit it
$(document.body).append(form);
form.submit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment