user3865639
user3865639

Reputation: 15

Escaping a Javascript Code Block and Function for PHP output

I keep getting ILLEGAL STRING or ILLEGAL TOKEN. Any thoughts? I imagine this is an escaping issue, but have not found the correct solution.I am escaping the single quotes as other code is escaped in the same area.

I have tried:

Here is the code:

<?php
  $STRING .='
    <script type="application/javascript">

     function onPictureChanged() 
     {

       var href="http://pinterest.com/pin/create/button/?url="\' +   encodeURIComponent(location.href.replace(location.hash, "")) + \'"&media="\' + $(\'#fullResImage\').attr(\'src\');


       jQuery(\'.pp_social\').append(“<div class=\'pinterest\' ><a href=\'”+ href +”\' class=\'pin-it-button\' count-layout=\'horizontal\' target=\'_blank\'><img border=\'0\' src=\'http://assets.pinterest.com/images/PinExt.png\' title=\'Pin It\' /></a></div>”);

     }
    </script>';

echo $STRING;

Upvotes: 0

Views: 302

Answers (2)

user3865639
user3865639

Reputation: 15

Ok, the answer was definitely the inaccurate escaping due to an attempt at many methods. The solution was a combination of the following:

  • Heredoc which greatly simplifies the escaping of output if not completely eliminates the need for it. Use variable within heredoc in PHP (SQL practice)
  • properly combining single and double quotes
  • Making sure no curly/fancy quotes were included... either from copy/pasting or my text editor ( See Alvaro's comment above)

@stefan Yes, you comment was definitely part of the issue! As the string was to be in a URL and not output to html.

Thanks for all you help. A fresh set of eyes always helps! Here is the final working code:

$STRING .= 

<<<MY_MARKER
<script type="application/javascript">

function onPictureChanged() 
{

    var href="http://pinterest.com/pin/create/button/?url="+encodeURIComponent(location.href.replace(location.hash,""))+"&media="+$('#fullResImage').attr('src');

    jQuery('.pp_social').append('<div class="pinterest"><a href="+ href +” class="pin-it-button" count-layout="horizontal" target="_blank"><img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></div>');

}

MY_MARKER;

Upvotes: 0

Stefan
Stefan

Reputation: 1258

You use a ” instead of " in some cases. i.e. ”+ href +”\ should br "+ href +"\

PS. Mac User? You can disable that 'helper' under Preferences -> Keyboard -> Text

Upvotes: 3

Related Questions