Skip to content

Instantly share code, notes, and snippets.

@tracker1
Created August 7, 2015 23:25
Show Gist options
  • Save tracker1/a3164409f6e84b801632 to your computer and use it in GitHub Desktop.
Save tracker1/a3164409f6e84b801632 to your computer and use it in GitHub Desktop.
Post JSON object as form
//assumes jQuery
import clone from 'safe-clone-deep'
import encode from './html-encode';
export default function postObjectFromForm(url, data, options = {}) {
data = clone(data);
//console.log('postObjectFromForm', {url, data, options});
var form = $(`<form method="post" action="${encode(url)}"></form>`);
if (options.target) form.attr('target', options.target);
addItemsToForm(form, typeof data == 'object' ? [] : [options.name || 'model'], data);
form.submit();
}
function addItemsToForm(form, names, obj) {
if (obj === undefined || obj === "" || obj === null) return addItemToForm(form, names, "");
if (
typeof obj == "string"
|| typeof obj == "number"
|| obj === true
|| obj === false
) return addItemToForm(form, names, obj);
if (obj instanceof Date) return addItemToForm(form, names, obj.toJSON());
// array or otherwise array-like
if (obj instanceof Array) {
return obj.forEach((v,i) => {
names.push(`[${i}]`);
addItemsToForm(form, names, v);
names.pop();
});
}
if (typeof obj === "object") {
return Object.keys(obj).forEach((k)=>{
names.push(k);
addItemsToForm(form, names, obj[k]);
names.pop();
});
}
}
function addItemToForm(form, names, value) {
var name = encode(names.join('.').replace(/\.\[/g, '['));
value = encode(value.toString());
//console.log('addItemToForm',name,value);
form.append(`<input type="hidden" name="${name}" value="${value}" />`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment