Javascript: Encoding Values in XML Strings for AJAX / Web 2.0

I have written a very simple javascript function to do the job. The function takes a Javascript string (or any value, integer etc.) as input, converts it into a string and then replaces all occurrences of <, >, &, ", and ' with their html values. Please note that on the server side e.g. in PHP, ASP you have to decode the xml values to process them properly. I have also written the PHP function, which is described here.

function xml_encode(input)
	if(input == undefined)	
		alert("error in xml_encode: input undefined");	
	input	=	trim(input.toString());
	var replace_with	=	'&amp;';
	// The 'g' in the first argument is used to tell the function 'replace' 
	// that all occurences (g = global)
	// of the character in between slashes have to be replaced.
	input 			= 	input.replace(/&/g,	replace_with);
	replace_with		=	'&lt;';
	input 			= 	input.replace(/</g,	replace_with);
	replace_with		=	'&gt;';
	input 			= 	input.replace(/>/g,	replace_with);
	replace_with		=	'&apos;';
	input 			= 	input.replace(/'/g,	replace_with);
	replace_with		=	'&quot;';
	input 			= 	input.replace(/"/g,	replace_with);
	return input;

Using xml_encode() - A simple example (JavaScript Code):

So, now let's say you want to create an XML string manually (in JavaScript) you'll use the function as follows:

	var xml		=	"<?xml version='1.0' standalone='yes'?>";
	name_variable	=	trim(document.getElementById('your_name').value);
	xml		+=	"<name>";
	xml		+=	xml_encode(name_variable);
	xml		+=	"</name>";

The trim function used in the example above is defined here.

Did this tutorial help a little? How about buy me a cup of coffee?

Buy me a coffee at

Please feel free to use the comments form below if you have any questions or need more explanation on anything. I recommend thoroughy testing on a production-like test system first before moving to production.