transformRequestAsFormPost

Fix transformRequestAsFormPost to handle arrays when submitting checkbox data in AngularJS.

by Ty Cahill

JavaScript

function serializeData( data ) {

            // Polyfill isArray for IE 8
            if (!Array.isArray) {
                Array.isArray = function(arg) {
                    return Object.prototype.toString.call(arg) === '[object Array]';
                };
            }

			// If this is not an object, defer to native stringification.
			if ( ! typeof data === 'object'  ) {
				return( ( data == null ) ? "" : data.toString() );
			}
			var buffer = [];

			// Serialize each key in the object.
			for ( var name in data ) {
				if ( ! data.hasOwnProperty( name ) ) {
					continue;
				}
				var value = data[ name ];
                
                // If this is an array, we need to loop through all array elements
                if(Array.isArray(value)){
                    for(i=0; i < value.length; i++){
                        var val = value[i];
                        buffer.push(
                            encodeURIComponent( name ) + "=" +
                            encodeURIComponent( ( val == null ) ? "" : val )
                        )
                    }
                }
                else{
                    buffer.push(
                        encodeURIComponent( name ) + "=" +
                        encodeURIComponent( ( value == null ) ? "" : value )
                    )
                }
			}
			// Serialize the buffer and clean it up for transportation.
			var source = buffer
				.join( "&" )
				.replace( /%20/g, "+" )
			;
			return( source );
		}



var data = { name: "Ty Cahill",
            website: "tythewebguy.com",
            cost: 1000000,
            crazy: true,
            weekend: ['Saturday', 'Sunday']
            }

$('body').append( serializeData( data ));