user391986
user391986

Reputation: 30906

expression engine fields in javascript

I am trying to get the content of a custom channel field (chan_body) inside a javascript variable (foo). I have set already in my config.php file
$config['protect_javascript'] = "n"; I have my chan_body 'Type' => 'TextArea' with 'Default Text Formatting => 'None' the problem is that this channel field is actually a couple lines long which is actually code in another language (that is not meant to be executed), but it's not getting escaped and just screwing up the javascript by getting dumped in there. How can I fix this? I tried escape() that did not help

{exp:channel:entries channel="mychannel" category="2"} 
    <script type="text/javascript">
        var foo = "{chan_body}";
        alert(foo);
    </script>    
{/exp:channel:entries}

translates to

<script type="text/javascript">
    var foo = "my $testing = "myfile.txt";
    Uncaught SyntaxError: Unexpected identifier
    open(FILE,"$myfile ") or die;
    # this is a comment
    alert(foo);
</script>    

Upvotes: 1

Views: 317

Answers (3)

Zaheer Abbass
Zaheer Abbass

Reputation: 399

You can use base64 encode to encode value in chain_body when assigning to foo and where ever you need to use that, you can decode it.

For example

var foo = BASE64_ENCODE("{chan_body}");

You can see here that how base64 stuff works in javascript. How can you encode a string to Base64 in JavaScript?

Upvotes: 2

unexplainedBacn
unexplainedBacn

Reputation: 768

JavaScript doesn't take too well to multi-line strings. See How to create multi-line strings. To inject it directly to a variable as written you'd need backslashes \ at the end of new lines, and also escape any double-quotation marks.

But who wants to do that?

A round-about way might be to place the contents of your field in a div with display:none and access it that way.

{exp:channel:entries channel="mychannel" category="2"} 
  <div id="entry-{entry_id}" style="display:none;">{chan_body}</div>

  <script>
    var foo = document.getElementById('entry-{entry_id}').innerHTML;
    alert(foo);
  </script>    
{/exp:channel:entries}

Upvotes: 1

dbf
dbf

Reputation: 3463

Missing a quote after $testing

var foo = "my $testing" = "myfile.txt";

Upvotes: 0

Related Questions