code everywhere

convert JS object to POST form data

posted on May 9, 2014, 12:24 am in js, nodejs

Most REST services communicate with JSON, but sometimes you run into a POST form. This code will serialize a JavaScript object to return form data that can be sent for a POST request.

var formStringify = function(obj) {
formData "";
    for (var 
key in obj) {
formData += key "=" encodeURIComponent(obj[key]) + "&";
formData formData.substring(0formData.length 1);

And its usage:

var data formStringify({ key 99key2 "bar"key3 "foo" });
console.logdata );

Check out your browser's console output to see the code in action.

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy