I'm writing mostly in PHP, but one function requires me to use JavaScript. I need to access a PHP variable in my JavaScript. I've placed the following code between the <head> tags:
<script>
$(document).ready(function(){
$(document).keyup(function(e) {
if ($('.pho_big').is(':visible') && e.keyCode==27) {
var js_link = '<?php echo $p_link; ?>';
window.location.href = js_link;
}
});
});
</script>
In short, when the esc key is pressed, I want to go to $p_link. So I'm trying to copy $p_link to js_link and go there. Instead of getting the contents of $p_link, my browser is trying to go to <?php%20echo($p_link)%20?>, which is obviously incorrect.
I've already gone here, here, and here, all of which seem to tell me to do exactly what I'm doing. My knowledge of JavaScript is near zero, so I'm probably missing something simple, but I don't know enough to know what or troubleshoot.
1 Answer 1
it looks like <?php echo $p_link; ?> is not interpreted by php.so js_link contains string <?php echo $p_link; ?>.when you set window.location.href to <?php echo $p_link; ?> . browser tries to go to [less_than]?php%20echo($p_link)%20?[greater_than] which is url encoding of <?php echo $p_link; ?>.
(sorry,since I have low reputation, I cant post comment)
3 Comments
<script>window.Js_link="<?php echo $p_link; ?>";</script>, somewhere in your php file (before including header.tpl) and use window.location.href=window.js_link; inside the event handling function.
$p_linkis an empty string or something that echos to that. Also please note that the way your doing it PHP is creating JavaScript on page load and so JavaScript will have a hard value of what$p_linkis at the time of the page render and not when the they key is pressed. If it's an echo problem tryvar_dumping it.jsand not.php.phpwill not be interpreted. Alsoincludeandrequirecan be thought of you just copying and pasting them inline into your file (from what I remember).