Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode HTML before POST

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

like image 998
oshirowanen Avatar asked Feb 04 '11 14:02

oshirowanen


People also ask

How do you encode data in HTML?

Encoding for HTML means converting reserved characters into HTML character entities. HTML character entities are written as &code; , where "code" is an abbreviation or a number to represent each character.

What is URL encoded in HTML?

URL encoding converts non-ASCII characters into a format that can be transmitted over the Internet. URL encoding replaces non-ASCII characters with a "%" followed by hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign, or %20.

What is HTML encoding and decoding?

HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.

What is HTML encoding explain with an example?

HTML encoding makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML. For example, if a text string contains a less than sign 9(<) or greater than sign (>), the browser would interpret these characters as the opening or closing bracket of an HTML tag.


1 Answers

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.

like image 86
George Stocker Avatar answered Sep 21 '22 19:09

George Stocker