How to echo script in php - php

I am using the shortcode execute plugin in wordpress.
This simply allows me to write shortcode like this [email_spamproof]
But I am trying to echo a script. Please see below...
<?php
echo '<script type="text/javascript">
<!--
// spam protected email
emailE=("enquiries#" + "example.co.uk")
document.write('<a title="E-mail Example" href="mailto:' + emailE + '">' + emailE + '</a>')
//-->
</script>
<noscript>
<span class="spam-protected">Email address protected by JavaScript. Please enable JavaScript.</span>
</noscript>';
?>
Now you can probably see my problem already.
Usually when I echo stuff it goes like this... echo 'hello';
And you break the string using the same apostrophes
- like this... echo 'hello ' . php_name() . ' and friends'
My Problem
The script also uses a similar method by adding script variables into the string, but these script apostrophes will get confused as PHP apostrophes, and break the echoed string.
How can I avoid this?
Thanks

The right code:
<?php
echo "<script type='text/javascript'>
<!--
// spam protected email
emailE=('enquiries#' + 'example.co.uk')
document.write('<a title='E-mail Example' href='mailto:' + emailE + ''>' + emailE + '</a>')
//-->
</script>
<noscript>
<span class='spam-protected'>Email address protected by JavaScript. Please enable JavaScript.</span>
</noscript>";
?>

The \ character is the escape character. Prepend one to each internal use of the character used to delimit the string.
Alternatively, use a HEREDOC.

It is easy. Save your javascript code in a new one file and then use this to load it:
include('myjavascript.php');
Then you will use the include option as a echo because the web will understand your code as HTML and you execute it when you want with php (like echo).

You could write " in your javasript code, and then only use single quotes(') in your php echo.
A more suitable method is to use escape characters in your javascript code "\'" (without the double quotes)

You can either escape them with a back slash: echo 'It\'s cold'; or use heredoc:
echo <<<END
lots of text here
END;

You need to escape them and then concatenate the variables :
(Also I dont know if you realize, but you are echoing a commented out section of javascript)
echo '<script type="text/javascript">
<!-- // spam protected email
emailE=("enquiries#" + "example.co.uk")
document.write(\'<a title="E-mail Example" href="mailto:'.emailE.'">'.emailE.'</a>\')
//-->
</script>
<noscript>
<span class="spam-protected">Email address protected by JavaScript. Please enable JavaScript.</span>
</noscript>';

Related

Calling Javascript - Window.open in PHP

I'm trying to call a window.open() javascript code inside a php file, but unfortunately it is not responding.
Here's my code:
<html>
<head>
<script language="JavaScript"></script>
</head>
<body>
<?php .....
$printHeader .= " <div id ='subHeader'><p class = 'alignleft'><font style='color:blue'>User: " . $username . " | Access: " . $level ." | <a href=logout.php>Logout</a></font></p>";
$printHeader .= " <p class='alignright'><a href='refresh.php' onClick='window.open(this.href,'mywin','width=400,height=200')'>Refresh List</a></p></div>";
$printHeader .= "<div style='clear: both;'></div>";
.... ?>
</body> </html>
Unfortunately, when I run it, it doesn't work at all. Can we not call javascript in php? Please advise!
Thanks!
I think the issue is related to the quotes, Your inner single quotes are ending the onClick string, so replacing the outter single quotes to double quotes(will keeping the inner quotes single) will solve your issue. try changing this:
onClick='window.open(this.href,'mywin','width=400,height=200)'
To this:
onClick=\"window.open(this.href,'mywin','width=400,height=200)\"
Here's an example:
On JSFiddle
Another solution is to simply escape your inner quotes by prefixing them with a backslash (\).
One thing that catches my eye right away is that you did not escape your single quotes withing the onclick event. Modify it like so:
onclick=\"window.open(this.href, 'mywin', width=400, height=200);\"
See if this helps you out.

using javascript quotes in php code

i'm having some trouble using javasript in php code, I'm confused in using double quotes and single quotes.
echo 'Delete';
or how to do the above code in php ?.
Thanks
use this code
echo 'Delete';
you have to escape the quotes.
http://viper-7.com/F6uI0L
You need to escape the quotes with htmlspecialchars (for HTML):
echo '<a href="..." onclick="return confirm('
.htmlspecialchars('"Are you sure"') . '">Delete</a>';
(alternatively you could just write ")
...but don't do that. Use JS event registration:
document.getElementById('a-id').addEventListener('click', function (e) {
if (!confirm("Are you sure...")) {
e.preventDefault();
}
});
Do that in JS file. It requires that the <a> have an ID (you could also do it with a host of other selectors, but ID is the simplest).
Change like following
echo "Delete";
Why don't you put the HTML outside of PHP tags? For example you could do:
...
?>
Delete
<?php
...
Another way to echo HTML is:
echo <<<HTML
Delete
HTML
Error in confirm("Are you sure you want to delete?")"> you need to escape double quote.
You need to call the javascript function using php echo
echo 'href_link';
...but you have to use JS function
<html><head><script type="text/javascript">
function fun()
{
if(confirm('are you sure')) return TRUE;
else return FALSE;
}
</script>
</head>
<body></body>
</html>

How to escape string from PHP for javascript?

lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->

How to escape Javascript code that is echoed in PHP

I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?
You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.
Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";
use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();
You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.
PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)
Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';

echoing a jquery animation function with php

I am trying to echo this jquery function, with php. basically if the script detects a field of a form is not filled in then it will echo this and make the input text box turn red.
It works fine when it is not being echo'd.
echo('
<script type="text/javascript">
$(document).ready(function() {
$(\'input\').animate({backgroundColor:\"#F00\"},200);
});
</script>
');
any ideas?
I don't think you have to escape your quotes when the string is within single quotes. PHP won't parse the string, it will be output literally.
You're over-doing it on the string escape. To keep it simple, just use single quotes around the echoed string, and use double quotes inside it. Something like:
echo('
<script type="text/javascript">
$(document).ready(function() {
$("input").animate({backgroundColor: "#F00"}, 200);
});
</script>
');
When you're echoing stuff, there are indeed some cases when you need to escape the quotes, but most of the times you can simply get away with it by using different types of quotes. For example, I'll never get it why people still do something like:
echo "<input type=\"text\" name=\"username\">";
as opposed to
echo '<input type="text" name="username">';
which makes your life a whole lot easier when you have to modify it.
Hope this helps !
You shouldn't use \" there, just "
Furthermore: a hex-color-value is no numeric value you can use for animate() .
By this, the error is fixed by removing the backslashes from the doublequotes, but your animation wouldn't show any effect.
i didnt test it, but try that:
$nl = "\n";
echo '<script type="text/javascript">'.$nl;
echo ' $(document).ready(function() {'.$nl;
echo ' $("input").animate({backgroundColor:"#F00"},200);'.$nl;
echo ' });'.$nl;
echo '</script>'.$nl;
the $nl="\n" is only for linebreak (I prefer to use singlequotes in echos, so php didn't have to parse the content - just echo out).

Categories