1

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>    
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user391986
  • 29,536
  • 39
  • 126
  • 205

3 Answers3

2

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?

Community
  • 1
  • 1
Zaheer Abbass
  • 359
  • 2
  • 4
1

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}
Community
  • 1
  • 1
unexplainedBacn
  • 768
  • 4
  • 13
  • thanks! will try although it might add a little complication given the javascript framework I'm working with I wanted to keep everything in objects – user391986 Sep 11 '12 at 14:33
0

Missing a quote after $testing

var foo = "my $testing" = "myfile.txt";
dbf
  • 3,278
  • 1
  • 24
  • 34
  • everything after foo = is what is inside the {chan_body} channel field when it runs, I am trying to get this string content inside the foo javascript variable. – user391986 Sep 10 '12 at 23:37
  • ah sorry, ok, so the {chan_body} delivers the content `"my $testing = "myfile.txt"`, then the content of chan_body is mixing up quotes, how is chan_body created or set, or how/where do you get it's value from? – dbf Sep 10 '12 at 23:44