Tutorial :Problems with javascript inside echo



Question:

I want to echo the following code:

<a href="http://delicious.com/save" onclick="window.open('http://delicious.com/save?v=5&noui&jump=close&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;" class="delicious" target="_blank">Add to Delicious</a>  

The problem is that Dreamweaver warns me on syntax errors I can not figure out. Who can spot the syntax errors? The html and script on its own works just fine - the problem comes with the php when it is echoed.


Solution:1

you can use:

<?php  echo '<a href="http://delicious.com/save" onclick="window.open(\'http://delicious.com/save?v=5&noui&jump=close&url=\'+encodeURIComponent(location.href)+\'&title=\'+encodeURIComponent(document.title), \'delicious\',\'toolbar=no,width=550,height=550\'); return false;" class="delicious" target="_blank">Add to Delicious</a>';  ?>  

not tested, but should work.


Solution:2

You shouldn't have & in HTML, these should be encoded to &amp;.

<a href="http://delicious.com/save" onclick="window.open('http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;" class="delicious" target="_blank">Add to Delicious</a>  

That's the only error I can spot.


Solution:3

You have to escape " chars :

echo "<a href=\"http://delicious.com/save\" onclick=\"window.open('http://delicious.com/save?v=5&noui&jump=close&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;\" class=\"delicious\" target=\"_blank\">Add to Delicious</a>";  

As bluesmoon said it's better written as :

echo <<<ENDOFECHO  <a href="http://delicious.com/save" onclick="window.open('http://delicious.com/save?v=5&noui&jump=close&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;" class="delicious" target="_blank">Add to Delicious</a>";  ENDOFECHO;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »