Skip to content

Instantly share code, notes, and snippets.

@ncou
Forked from hom3chuk/jquery.post.js
Created November 11, 2016 16:08
Show Gist options
  • Save ncou/dbe6f78d3bd4da7c8543919e5e88396a to your computer and use it in GitHub Desktop.
Save ncou/dbe6f78d3bd4da7c8543919e5e88396a to your computer and use it in GitHub Desktop.
// See https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit, jQuery version with arrays and objects support
function post(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, 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);
}
});
$(document.body).append(form);
form.submit();
}
@ncou
Copy link
Author

ncou commented Nov 11, 2016

post('/contact/', {name: 'Johnny Bravo'});

@ncou
Copy link
Author

ncou commented Nov 11, 2016

Vanilla implementation :

function post(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.
    // The rest of this code assumes you are not using a library.

    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment