This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Possible Duplicate:
Passing PHP variable into JavaScript
I want to obtain a PHP variable, to use it in an if-condition in JavaScript.
I was trying to use it like this:
var phpLogin = <?php $_SESSION['login'] ?>;
But it's wrong in syntax terms. So, how can I use a PHP variable in JavaScript?
Use json_encode and don't forget echo.
var phpLogin = <?php echo json_encode($_SESSION['login']) ?>;
You forgot the echo.
<?php echo $_SESSION['login']; ?>
or just
<?=$_SESSION['login']?>
The problem in your code is that you forgot the echo:
var phpLogin = <?php echo $_SESSION['login'] ?>;
Try:
var phpLogin = "<?php =$_SESSION['login']; ?>";
It may look like overkill, but for safety reasons you should use json_encode when echo'ing directly to PHP:
var phpLogin = <?=json_encode($_SESSION['login'])?>;
Or, in its longer form:
var phpLogin = <?php echo json_encode($_SESSION['login']); ?>;
Or, to also accept empty sessions:
var phpLogin = <?php echo #json_encode($_SESSION['login']); ?>;
This will simply output NULL when there's no login session.
Related
This question already has answers here:
GET URL parameter in PHP
(7 answers)
Closed 6 years ago.
I'm trying to get page number from web address like beds.html?page=3
but, if I use php get method, then it's not returning anything.
I hope to find any easy solution.
cheers
If You Want that parameter on html page then you have to use javascript for it
<script>
var param1var = getQueryVariable("page");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
if you are on php page simply use
<?php
echo $_GET['page'];
?>
you can get page like this:
<?php
$_REQUEST['page'];
?>
and also you can type echo before $|_REQUEST to check you are getting proper page number or not
get is the right method to use.
<?php
$_GET['page'];
?>
I have a problem with my script. If I have two JSON_ENCODE lines my script doesn't work anymore.
var time= <?php echo json_encode($time_cell); ?>;
var time2= <?php echo json_encode($time_cell2); ?>;
Why? Is there any other method to get this PHP vars?
JSON encoded string needs to be parsed in Javascript.
You can do somthing like this:
var time=JSON.parse("<?php echo json_encode($time_cell); ?>");
var time2=JSON.parse("<?php echo json_encode($time_cell2); ?>");
You mey read more here on this link.
This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
Yes I know this question gets asked a lot, but I'm fairly new to JS and I need to use a php variable in some JS. I'm more then aware that PHP is executed server side and JS is client side however other people claim that this works.
I've got a PHP variable called "test1" that I want to log to the JS console (for instance):
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>';
?>
What this does is print " " to the JS console. Not exactly what I was hoping for.
Now this may not even be doable and I may have to pass the variable off the page and back in again with AJAX, but I'd rather have a quick and easy solution if there is one available!
Any help is appreciated.
You could do this.
<script>
var JSvar = "<?= $phpVar ?>";
</script>
The PHP will be parsed and the value of $phpVar will become the value of JSvar whatever.
Make sure you encode phpVar properly. For example, if phpVar contains a double quote, you'll end up with a broken JS
Use this no need to give "" => change to '.$test1.'..
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "'.$test1.'"
console.log(carnr);
</script>';
?>
try
<?php $test1 = '1'; ?>
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>
Generally, it is better to not print static stuff with php, but to have static (that is unchanging) stuff directly in HTML and only use PHP on the parts that really need it.
You made a mistake do it so:
<?php
$test1 = '1';
echo '<script type="text/javascript"> var carnr; carnr = "'.$test1.'" console.log(carnr)</script>';
?>
Since you're writing your JS with your PHP, you can simply do:
$test1 = "blah";
echo "<script type=\"text/javascript\">console.log($test1);</script>";
You are already in open php tag. When printing the line just append the variable to the output by using a dot.
Example:
print 'variable1 '.$variable1.' is now printed';
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So far I know two ways to pass php variables to javascript.
One is by using
<script>
$(document).ready(function()
phpvalue=$("#hiddeninput").val()
})
</script>
<input type="hidden" id="hiddeninput" value="phpvalue">
And the other one is by having for example a button and using onclick
<script>
function clickf(phpvalue) {
}
</script>
<input type="submit" onclick="clickf(<?php echo phpvalue ?>)">
All of them work great but:
Is there any other way that I'm missing?
Which one is the "best"?
Any chance that I can use inside the script or the external js ?
<script>
$(document).ready(function()
var phpvalue = <?php echo $var; ?>
});
</script>
Like others already answered, just put a PHP tag whereever you would place the JS value, like var foo = <?= $php_value ?>; or var foo = <?php echo $php_value ?>;.
If you want to use this in an external JavaScript file, you have to make sure .js files get parsed by PHP. If this is not an option for you (for example, your host doesn't allow it), I suggest you set the values in a <script> tag inside your <head> and then just reference thos variables from your external JavaScript. In that case, I would strongly suggest you namespace them like var app_vars = { foo: <?= $bar ?> } in order to not clutter the global object.
Another way would be to retreive the values via Ajax. But the viability of this approach depends on your use case.
And another hint: if you want to pass multiple variables or arrays, there's JSON baked into PHP since version 5.2:
<?php
$my_complex_var = array(
'array' => array('foo', 'bar'),
'val2' => 'hello world'
);
?>
<script>
var my_complex_js_var = <?= json_encode($my_complex_var) ?>
</script>
<script>
var javascript_variable = <?php echo $php_variable; ?>;
</script>
Instead of assigning values to hidden inputs, you could just generate JavaScript directly:
$script = <<<EOT
<script>
var phpvalue = $phpvalue;
</script>
EOT;
echo $script;
for the top example you do not need to use val you could use any attr you like.
For example
phpvalue="myvalue"
then within jquery
$("#hiddeninput").attr("phpvalue");
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I've run into an odd issue in a PHP script that I'm writing-- I'm sure there's an easy answer but I'm not seeing it.
I'm pulling some vars from a DB using PHP, then passing those values into a Javascript that is getting built dynamically in PHP. Something like this:
$myvar = (bool) $db_return->myvar;
$js = "<script type=text/javascript>
var myvar = " . $myvar . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
The problem is that if the boolean value in the DB for "myvar" is false, then the instance of myvar in the $js is null, not false, and this is breaking the script.
Is there a way to properly pass the value false into the myvar variable?
Thanks!
use json_encode(). It'll convert from native PHP types to native Javascript types:
var myvar = <?php echo json_encode($my_var); ?>;
and will also take care of any escaping necessary to turn that into valid javascript.
This is the simplest solution:
Just use var_export($myvar) instead of $myvar in $js;
$js = "<script type=text/javascript>
var myvar = " . var_export($myvar) . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
Note: var_export() is compatible with PHP 4.2.0+
$js = "<script type=text/javascript>
var myvar = " . ($myvar ? 'true' : 'false') . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";