Page 1 of 1

Assign multiline text to textarea using ajax

Posted: Sat Jan 02, 2010 4:58 am
by vadapalli
Hi all

I want to add multiline text to textarea using ajax, i did that by escaping newline characters, you can see following snnipet

// Ajax server side code //
<?php

mysql_connect('localhost','root','');
mysql_select_db('test');

$getCommentInfo = " SELECT * FROM get_data ";
$resCommentInfo = mysql_query($getCommentInfo);
$fetCommentInfo = mysql_fetch_assoc($resCommentInfo);

$commentText = $fetCommentInfo[text_node];



$data1 = str_replace(array("\r\n" , "\r", "\n"), "\n", trim($commentText));


echo "document.getElementById('txt_area_1').value = '".addslashes($data1)."';";

?>

////////////////////////

But the above script is completely removing newline,

for example assume the data in database table is like
Ranganth V,
D.No:2-20-56,
India

In three lines if i use above script its coming in one line, but i want assign text newline character,it giving javascript error :" unterminated string literal ".

Please help me...

Thanks in advance

Re: Assign multiline text to textarea using ajax

Posted: Sat Jan 02, 2010 6:59 am
by requinix
addslashes() won't escape newline characters. Your script will generate output like

Code: Select all

document.getElementById('txt_area_1').value = 'This
is
a
multiline
string';
JavaScript doesn't allow strings spanning multiple lines like PHP does.

I suggest you use AJAX in the way it was intended - to move data, not code - but most people don't care about doing things in a better way, so here is where I mention that addcslashes will escape whatever characters you tell it to.

Re: Assign multiline text to textarea using ajax

Posted: Sat Jan 02, 2010 7:14 am
by kaszu

Code: Select all

$data1 = str_replace(array("\r\n" , "\r", "\n"), "\n\\", trim($commentText));
This will generate output

Code: Select all

document.getElementById('txt_area_1').value = 'This\
is\
a\
multiline\
string';
this is a valid JS string.