- Welcome to Geeksww.com
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"); return; } input = trim(input.toString()); var replace_with = '&'; // 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 = '<'; input = input.replace(/</g, replace_with); replace_with = '>'; input = input.replace(/>/g, replace_with); replace_with = '''; input = input.replace(/'/g, replace_with); replace_with = '"'; 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?
Please feel free to use the comments form below if you have any questions or need more explanation on anything. I do not guarantee a response.
IMPORTANT: You must thoroughy test any instructions on a production-like test environment first before trying anything on production systems. And, make sure it is tested for security, privacy, and safety. See our terms here.
tags cloud
popular searches
free download for mysql database server 5.1.5, bison, gearman, source code, php, install cairo, laptop, mysql, java, linux, install mysql, mysql initialization, mysql mysql, tools, ubuntu
Similar Tutorials:
- Removing Whitespaces from Beginning of a String (Left Trim), using Javascript
- Removing Ending Whitespaces from a String (Right Trim), using Javascript
- Trim whitespaces from both ends of a string, using Javascript
- Bundle, validate, compress javascript files
- Sleep/Pause for specified number of seconds
Tutorials in 'Web Development > Javascript' (more):
- How to write a function that generates random string in Javascript?
- Which frontend framework should i learn?
- Bundle, validate, compress javascript files
- How to execute a function at regular intervals using Javascript
- Go to Top of the Page Using Javascript
Comments (write a comment):
0 comments so far. Be the first one to leave a comment on this article.
leave a comment