Weird JavaScript XML Problem

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
I guess I have gotten a lot better at solving my own problems; I have not asked for help here in a long time, but this issue I can't seem to understand although I solved it. I have been a making a support chat script, which works to get data to the client by Database -> PHP -> XML -> JavaScript -> HTML and vise versa. To protect my users, and the script, I used htmlspecialchars() on the inputted text (PDO protects the database). The XML escapes fine but when I load the data from the XML return into the JavaScript, it is unencoded again. I can't find why, there seems to be no documentation on it. I solved the issue by double escaping with htmlspecialchars() to compensate, but I would like to know why.

The returned XML for the server.
Code:
<chat>
  <connection>
    <status>connected</status>
  </connection>
  <updates>
    <message>
      <user>Test1</user>
      <time>1282436270</time>
      <type>user</type>
      <text>&lt;hello&gt;&lt;/hello&gt;</text>
    </message>
  </updates>
</chat>

The JavaScript parser.
Code:
var messages = chat.lastChild.getElementsByTagName('message');
for (var i = 0; i < messages.length; i++) {
  var message = new Object();
  for (var b = 0; b < messages[i].childNodes.length; b++) {
     var prop = messages[i].childNodes[b];
     if (prop.hasChildNodes()) {
       message[prop.nodeName] = prop.firstChild.nodeValue;
     } else {
       message[prop.nodeName] = '';
     }
  }
  this.chatbox.createMessage(message['type'], message['text'], message['time'], message['user']);
}

The end result in the browser looks blank, but with a closer inspection of firebug you can see that the browser has hidden it as a html tag. Inspecting with firebug, I am sure that the problem does not extend beyond that.
 
Last edited:

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
That makes sense, think of it like this:
The first encode prevents it from thinking it is XML and makes it parse it as HTML
The second code prevents it from thinking it is HTML and parses it as plaintext

However, there is a nice alternative you can use that'll mean you only need to do it once:
Code:
<chat>
  <connection>
    <status>connected</status>
  </connection>
  <updates>
    <message>
      <user>Test1</user>
      <time>1282436270</time>
      <type>user</type>
      <text><![CDATA[&lt;hello&gt;&lt;/hello&gt;]]></text>
    </message>
  </updates>
</chat>
 
Top