I’m writing a lot of code most evenings. Here is some code I wrote in JavaScript to submit an AJAX request using multipart/form-data encoding. This is better than the more typical application/x-www-form-urlencoded encoding because data does not need to be reformatted if it contains things that are not allowed in a URL like spaces and ampersands. Spaces might be ok but the ampersands are delimiters for application/x-www-form-urlencoded data.

The PHP script on the server side is so simple that I won’t include it. It has at least one line that reads the appropriate form field in the $_POST array.

The JavaScript:

function SumbitAJAXConfig()
	ConfigUpdateRequest = new XMLHttpRequest();
	if( ConfigUpdateRequest == undefined || ConfigUpdateRequest == null )
		ConfigUpdateRequest.onreadystatechange = function()
		if( ConfigUpdateRequest.readyState == 4 && ConfigUpdateRequest.status == 200 )
			alert( "Did the update." );
		else if( ConfigUpdateRequest.readyState == 4 && ConfigUpdateRequest.status == 404 ) 
			alert( "Unable to update at this time." );
		ConfigUpdateRequest.open( "POST", "updateconfig.php?t=" + Math.random(), true );
	var boundary = '---------------------------' + Math.floor(Math.random()*32768) + Math.floor(Math.random()*32768) + Math.floor(Math.random()*32768);
	ConfigUpdateRequest.setRequestHeader( "Content-Type", 'multipart/form-data; boundary=' + boundary );
	var body = '';
	body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="';
	body += "newconfig";
	body += '"\r\n\r\n';
	var ConfigField = document.getElementById( "configfield" );
	body += ConfigField.value;
	body += '\r\n'
	body += '--' + boundary + '--';
	ConfigUpdateRequest.send( body );

This is not all my code. I got this from the internet. I am essentially duplicating someone else’s post from their blog or forum because this seems useful.

The content-length header is not written here because most browsers now reject it and figure out the value themselves. That keeps evil JavaScript from using incorrect values for nefarious purposes. I’m not sure why they bother since writing a non-client-browser program to submit incorrect data like that is trivial to an experienced programmer. Maybe they want to make sure someone doesn’t use someone else’s browser for that purpose.

If there was more than one form field to submit, each would be preceded by a boundary string and have the same formatting as the single field that I am sending.

I have updated code for more realistic form data in this post.