Encode HTML before POST

oshirowanen picture oshirowanen · Feb 4, 2011 · Viewed 22.8k times · Source

I have the following script, which encodes some of the value it receives propertly, but it does not seem to encode double quotes.

How do I encode the full value properly before posting?

function htmlEncode(value){ 
    return $('<div/>').text(value).html(); 
} 

The above script give me this:

&lt;p&gt;Test&amp;nbsp; &lt;span style="color: #ffffff"&gt;&lt;strong&gt;&lt;span style="background-color: #ff0000"&gt;1+1+1=3&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;

I need it to give me this:

&lt;p&gt;Test&amp;nbsp; &lt;span style=&quot;color: #ffffff&quot;&gt;&lt;strong&gt;&lt;span style=&quot;background-color: #ff0000&quot;&gt;1+1+1=3&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;

EDIT: Followup question: Encoded HTML in database back to page

Answer

George Stocker picture George Stocker · Feb 4, 2011

You shouldn't try to encode things with JavaScript.

You should encode it serverside.

Anything that can be done with JavaScript can be undone.

It is valid to encode it in JavaScript if you also check that it was encoded on the server, but keep in mind: JavaScript can be disabled.