Assign multiline text to textarea using ajax

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
vadapalli
Forum Newbie
Posts: 1
Joined: Sat Jan 02, 2010 4:02 am

Assign multiline text to textarea using ajax

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Assign multiline text to textarea using ajax

Post 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.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Assign multiline text to textarea using ajax

Post 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.
Post Reply