0

I have a textarea in my html and a button in bottom.when button press I want to add the content of the textarea in Database and with JQuery I want to show it in the DOM but this is vulnerable because someone may be write this:

<script> some bad code here </script>

how can I prevent to execute this code while insert in DOM and show it instead of run it(like facebook insert post that show the <script> tag and don't allow to execute it)

is this vulnerability the only way to attack to textarea form ?

mojibuntu
  • 307
  • 3
  • 16
  • how are you echoing this? I mean how are you showing this on the page? php echo ? something else? – SoWhat Nov 07 '13 at 07:16
  • 1
    You need to HTML-encode/escape the text before adding it to the DOM: http://stackoverflow.com/questions/1219860/html-encoding-in-javascript-jquery – Christofer Eliasson Nov 07 '13 at 07:18
  • 1
    Since you talk about adding it to a database, you should be sure to protect your self against [SQL-injections](http://en.wikipedia.org/wiki/SQL_injection) as well. – Christofer Eliasson Nov 07 '13 at 07:22
  • thanks @ChristoferEliasson I must study about encoding and escaping the text in DOM.I use django framework how can I prevent sql injection in save the data in database ? – mojibuntu Nov 07 '13 at 07:25
  • @SomeshMukherjee sorry but I don't understand what you say exactly ? what you mean about `echo` ? – mojibuntu Nov 07 '13 at 07:26
  • These things are most probably already taken care. Please show us how you accept the value of text area and store it in the database, how you fetch it from the db and then display it in your view. – SoWhat Nov 07 '13 at 07:34

2 Answers2

1

What if you pass the textarea value through a function like this one:

var escapeTags = function(str) {
   return str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

Of course, it is better to do this server side.

Krasimir
  • 13,306
  • 3
  • 40
  • 55
1

The preferred way is to use the text function in jQuery, because that will set text without invoking the Javascript interpreter.

$("#txt_div").text("<script>alert('hello');</script>");

Here is a live example on jsbin.

Sam King
  • 113
  • 6