A client-side script takes the text within a text input, “wraps” it within an XML block and sends it to a server that stores the information in a MySQL database.
As a first step before wrapping the input value, I escape the “&” characters like so:
var copyright = copyright.replace(/&/g,"&");
The resulting XML data block is sent to the server using jquery’s ajax method:
var copyright = copyright.replace(/&/g,"&"),
xml = "<request><session>"+session+"</session><space>"+space_id+"</space><view>"+view_id+"</view><copyright>"+copyright+"</copyright></request>",
url = "hidden URL";
$.ajax({
type: "POST",
url: url,
contentType: "text/xml; charset=UTF-8",
dataType: "xml;charset=UTF-8",
data: xml
});
Later after this operation, the content that was previously saved within the database needs to be retrieved and displayed within a web page:
$.ajax({
type: "POST",
url: url,
dataType: 'xml',
data: xmlString,
success: function(xml) {
var XML = $(xml);
// Process the data retrieved
},
error: function(jqXHR, textStatus, errorThrown) {
var XML = $(jqXHR.responseText);
console.log("error: "+textStatus+"\n"+errorThrown);
}
});
If an ampersand was typed in the input field and then saved, when trying to load the page that displays the same previously saved content, the ajax call breaks and runs down the error event handler, with the following error:
error: parsererror
Error: Invalid XML: <?xml version="1.0" encoding="UTF-8"?><response><target>
<target_id>2095466</target_id>
<plot>20029/13</plot>
<builder>Lemminkäinen</builder>
<housing_form>vm</housing_form>
<block_name></block_name>
<finnish_year>2013</finnish_year>
<target_name>As Oy Helsingin Saukonranta</target_name>
<target_address>Saukonpaadenranta 8</target_address>
<office_space></office_space>
<purpose></purpose>
<reservations></reservations>
<contacts></contacts>
<infoflag>2</infoflag>
<views>
<view>
<view_id>2095468</view_id>
<copyright>B&M</copyright>
</view>
</views>
</target>
<status>OK</status><errormsg></errormsg></response>
What is it that I’m doing wrong? Am I escaping the characters wrongly, or is it something else?
This question may seem to be a duplicate, but to me it doesn’t seem like it since the ampersand characters have been escaped prior to being stored. I even tried adding additional (1, then two) amp;s to the escape string, but the result is EXACTLY the same.
It turns out that the problem actually came from the server (to which I did not have access), the script that handled the requests did not escape the ampersand characters correctly, even though they were on the client-side.
Bellow is a JavaScript function that escapes all (?) special characters used with XML, just in case someone needs it: