0

Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)

Hy, so my problem is that i have a textarea which is generated with jquery, like this:

$var input = $('<textarea name="somename"></textarea>');
$(something).after(input);

But i also want to fill this textarea with content (when content exists of course), using php. sp now my code looks like this:

$var input = $('<textarea name="somename"><?=$variabel[0][something];?</textarea>');
$(something).after(input);

So the problem with this is that when i run this code the javascript automatically fills the content of the textarea in that input variable, and because there is more than one line it breaks so i get an error saying "Unexpected token ILLEGAL"

I hope i explained it well, so i need somehow the put the content of the textarea inside that generated textarea, but in a way in which my input doesn't break.

Thans for any advice!

Community
  • 1
  • 1
Mr. Sam
  • 790
  • 2
  • 9
  • 31

4 Answers4

0

remove the $ it's not a php variable, try this:

var input = $('<textarea name="somename"></textarea>');
$(something).after(input);
$('textarea[name="somename"]').val( <?php echo $variabel[0]['something']; ?> )
Ram
  • 143,282
  • 16
  • 168
  • 197
0

You can use the php function json_encode() to encode your PHP variable before it is output. It will convert newlines to \n, for example. More details about the function can be found here

http://php.net/manual/en/function.json-encode.php

In your case it would be something like this:

var input = '<textarea name="somename"><?= json_encode($variabel[0][something]); ?></textarea>';

Also refer to the following question: Pass a PHP string to a JavaScript variable (and escape newlines)

Community
  • 1
  • 1
compid
  • 1,313
  • 9
  • 15
  • No problem. Also I think `json_encode()` is a better alternative to `htmlentities()` as it was made specifically for javascript – compid Jun 14 '12 at 08:26
-1

Try this:

var $input = $('<?php echo "<textarea name=\"somename\">".htmlentities($variable[0]['something'])."</textarea>" ?>');
flowfree
  • 16,356
  • 12
  • 52
  • 76
-1

The problem is a syntax error, you needed a > to close your PHP tag:

$var input = $('<textarea name="somename"><?=$var;?></textarea>');

This error can be easily detected by using a console, which is built into Chrome. Or if you use Firefox you can an extention called Firebug.

Sem
  • 4,477
  • 4
  • 33
  • 52