Load the text data as JSON in textarea and you will not be able to execute it (javascript)

I have a silly problem loading data from a database into textarea using jquery-ajax.

The problem is that when I try to load data (send echo json_encode () from PHP from the database to TEXT utf8_general_ci) in a text field that I cannot use htmlentities (because characters are displayed in textarea, not text) if I put javascript in the database, and then upload to textarea, this download fix the characters, but .. execute the code and show me the javascript result.

Example:

<?php if (!empty($_GET['json'])) { $array = array( 'text1' => 'hello world!', 'text2' => '<script>alert("bu")</script>', ); echo json_encode($array); die(); } ?> <script type="text/javascript" src="jquery-1.6.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $.ajax({ url: "?json=true", type: "POST", dataType: "json", success: function(data){ $('textarea[name=area]').val(data.text2); } }); }); </script> <textarea name="area" cols="80" rows="6"></textarea> 

I am trying to use .val () ,. html (), data.text2.tostring () (fail) and nothing works, always execute the code. I think this is a simple glitch, but there is no solution if I need to show the correct code in textarea and no special characters. Any idea?

+4
source share
3 answers

TEXTAREA does not matter. It contains data between tags. Try using:

 $('textarea[name=area]').html(data.text2); 
0
source

This code works for me: http://jsfiddle.net/8WXyk/1/

In any case, I do not know if this is an acceptable solution for your needs.

Basically the code:

  • Retrieves escaped content from the server
  • Unescapes and inserts it into textarea (you should use .html () as pointed out by Asken)

This code uses the unescape function from the unescape plugin, which can be found here: http://plugins.jquery.com/files/jquery.unescape.js_0.txt

0
source

Try:

 $('textarea[name=area]').val(data.text2); 

instead of HTML. This will close the text area and allow you to insert a new value.

0
source

Source: https://habr.com/ru/post/1369112/


All Articles