Passing var from php to javascript - php

I try to do something pretty strait... getting php value to javascript
here is the page
here is the code..
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php $imagepath; ?>
alert (whatisthepath);
</script>
ALWAYS getting UNDEFINE.... why ?
--
Final wordking optimized code :
alert ("<?php echo $_REQUEST["path"]; ?>");

Missing: quotes around the var, php output to js var, semicolon after var setting:
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = "<?php echo $imagepath; ?>";
alert (whatisthepath);
</script>

All strings in JavaScript need to be surrounded with quotes. For example:
var whatisthepath = "<?php $imagepath; ?>";
The other issue is that you are not actually printing the string. All the above line of code will result in is an empty set of quotes. The correct way to do it would be to echo the imagepath
var whatisthepath = "<?php echo $imagepath; ?>"

For exactly this purpose, PHP offers the shorthand notation of <?= ... ?>. To output to value of the variable $imagepath, you can use <?= $imagepath ?>. For this to work, the short_open_path ini variable must be set to true. This may not be the default of your web server.
So, this turns the code into
<?php
ini_set('short_open_tag', TRUE);
$imagepath = SOME_VALUE;
?>
<script language="javascript">
var whatisthepath = "<?= imagepath ?>";
alert(whatisthepath);
</script>
Changing the ini value may not be convenient if it's just about a few variables, but if it happens more often in the code, I tend to find it make things more readable.

You forgot to add an echo or print statement in front of your $imagepath
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php echo $imagepath; ?>
alert (whatisthepath);
</script>
PHP is a serversided language while javascript is a client side language. Which means you have to threat it the same way you would threat HTML.
For example:
<div><?php echo $content; ?></div>
Hopefully this will give you a better understanding...

You can use json_encode() to ensure that the variable is properly escaped and quoted etc. for javascript. e.g.:
<?php $imagepath = $_REQUEST["path"]; ?>
<script language="javascript">
var whatisthepath = <?php echo json_encode($imagepath); ?> ;
alert (whatisthepath);
</script>

You should use to ensure that the variable has correct JS syntax.
<script language="javascript">
<?php $imagepath = $_REQUEST["path"]; ?>
var whatisthepath = <?php echo json_encode($imagepath); ?>;
alert (whatisthepath);
</script>

Related

assign a php variable to a sessionStorage var

I am trying to set a php variable value to a HTML5 sessionStorage. Is this feasible? Check my code below:
<script>sessionStorage.username = </script><php echo $_GET["user"]; ?>
Thank you in advance
Try this:
<script>
sessionStorage.username = '<?php echo $_GET["user"]; ?>';
</script>
Code edited

How to add php content or variable inside javascript alert box?! javascript, php, alertbox

How can i add php content or php variable inside Java-script alert box?!
I tried to make it work few ways but it is only popping up a blank box rather than the contents of php variable.
Here is the code:
<script language="javascript">
$(document).ready(function() {
$("#a").blur(function() {
<?php $b = $_POST['a'];
if(isset($_POST['update'])) {
mysql_query("UPDATE tbl_travel set fld_a='".$_POST[$b]."' where fld_id = '".$_POST["id"]."' ") or die(mysql_error());
} ?>
alert (<?php $b ?>);
});
});
</script>
Thank You for your Help :)
Change this
alert (<?php $b ?>);
to this
alert ('<?php echo $b; ?>');
You need to output the value of $b and add quotes inside the alert.
About PHP - echo
Have you tried this?
alert ('<?php echo $b ?>');
I use it like this
$text="Example PHP Variable Message";
echo '<script type="text/javascript">alert("'.$text.'")</script>';
1.
<script>
alert("</script><?php $r=5;echo $r;?> <script>")
</script>
you have to script off on when php start
This worked for me :
alert ("<?php echo $b; ?>");

can't pass php session variable to javascript string variable

Can't pass php session variable to javascript string variable
While the $_SESSION['Id'] variable exists, the javascript can't seem to bring it at least with this syntax:
CODE
<?php session_start(); ?>
<script>
var a = "<?php echo $_SESSION['Id']; ?>";
alert(a);
</script>
Your syntax looks fine. What happens if you write this?
<?php
php session_start();
echo '<div style="padding:30px; background-color:#ffffff;"><pre>'.print_r($_SESSION, true).'</pre></div>';
?>
<script>
var a = "<?php echo $_SESSION['Id']; ?>";
alert(a);
</script>
If that doesn't work then try manually setting the ID before the echo
<?php
php session_start();
$_SESSION['Id'] = 'AN ID!!!';
echo '<div style="padding:30px; background-color:#ffffff;"><pre>'.print_r($_SESSION, true).'</pre></div>';
?>
First, like the comments have mentioned, make sure you're using the correct case of id, whether it's id or Id.
Second, try using json_encode to convert it for javascript use. No need for "":
var a = <?php echo json_encode($_SESSION['Id']); ?>;
Try this to see if the variable $_SESSION['Id'] exists and is set to something
<?php
session_start();
print_r( $_SESSION );
?>
<script type="text/javascript">
var a = "<?php echo $_SESSION['Id']; ?>";
alert(a);
</script>

Javascript String with Single Quote printed from PHP code

I have following script printed from PHP . If some one has a single quote in description it shows javascript error missing ; as it thinks string terminated .
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '{$_REQUEST['title']}';
Obj.description = '{$_REQUEST['description']}';
</script>";
Form does a post to this page and title and description comes from textbox.Also I am unable to put double quotes around {$_REQUEST['title']} as it shows syntax error . How can I handle this ?
a more clean (and secure) way to do it (imo):
<?php
//code here
$title = addslashes(strip_tags($_REQUEST['title']));
$description = addslashes(strip_tags($_REQUEST['description']));
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = '<?php echo $title?>';
Obj.description = '<?php echo $description?>';
</script>
You also need to be careful with things like line breaks. JavaScript strings can't span over multiple lines. json_encode is the way to go. (Adding this as new answer because of code example.)
<?php
$_REQUEST = array(
'title' => 'That\'s cool',
'description' => 'That\'s "hot"
& not cool</script>'
);
?>
<script type="text/javascript">
var Obj = new Array();
Obj.title = <?php echo json_encode($_REQUEST['title'], JSON_HEX_TAG); ?>;
Obj.description = <?php echo json_encode($_REQUEST['description'], JSON_HEX_TAG); ?>;
alert(Obj.title + "\n" + Obj.description);
</script>
Edit (2016-Nov-15): Adds JSON_HEX_TAG parameter to json_encode calls. I hope this solves all issues when writing data into JavaScript within <script> elements. There are some rather annoying corner cases.
Use the string concatenation operator:
http://php.net/manual/en/language.operators.string.php
print "<script type=\"text/javascript\">\n
var Obj = new Array();\n
Obj.title = '".$_REQUEST['title']."';
Obj.description = '".$_REQUEST['description']."';
</script>";

very simple javascript failing

Working Example:
This is almost identical to code I use in another places on my page but fails here for some reason.
<?php
//$p = "test";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = "test";
</script>
Failing example: (alert still works)
<?php
$p = "test of the var";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = '<?php $p; ?>';
</script>
Try
'<?php echo $p; ?>';
or
'<?= $p ?>';
Debugging 101: Start checking all variable values.
alert(parent);
alert(parent.document);
alert(parent.document.getElementById('posts'));
as well as the value rendered by: '<?php $p; ?>'
Make sure your 'posts' object (I guess it is DIV or SPAN) loads before you fill it using javascript.
You're trying to generate javascript with php, here I use a simple echo:
<?php
$p = "test of the var";
echo"
<div id='posts'></div>
<script type='text/javascript'>
var posts = document.getElementById('posts');
posts.innerHTML = '$p';
</script>
";
?>
Note the $p and that the div is printed before the javascript!
You are not outputting the variable data is why it isn't working. You need to echo or print the variable $p.
In your example the $p is being evaluated, not printed.
To print it you should use print, echo, or the syntax <\?=$p;?>. without the \

Categories