code everywhere
technology, web services and applications

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) {
    var 
formData "";
    for (var 
key in obj) {
        
formData += key "=" encodeURIComponent(obj[key]) + "&";
    }
    
formData formData.substring(0formData.length 1);
    return 
formData;
};

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