I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script.
for eg:
<?
$divtohide = "adiv";
?>
<script language="javascript">
function hidediv($divtohide) {
................
}
</script>
Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal:
function hidediv(divtohide) {
// Your code may differ here, mine's just for example
document.getElementById(divtohide).style.display = 'none';
}
And print out the PHP variable only when you're calling it, within a pair of quotes:
hidediv("<?php echo addslashes($divtohide); ?>");
addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break.
as BoltClock wrote, use php to pass the variable.
but you can do it by most simple way, just write hidediv("<?=$divtohide?>")
<script type="text/javascript">
function hidediv() {
divobj = document.getElementById('<?= $divtohide ?>');
divobj.style.display = 'none';
}
</script>
Related
I am passing a PHP variable to Javascript, but only at a specific point in the code. As the PHP code continues, the variable I need changes. I could easily just run the Javascript and grab the PHP variable when the page is done loading, but that won't pass the information I want. I want the Javascript to grab the PHP variable at that point, and then ignore subsequent changes to it.
The actual program I'm working with is several thousand lines of code, so I created a simple page to mess around with this issue. The code below shows what I'm trying to do.
<?php
$php_var = 'something';
if(true) {
$php_var = 'new';
echo '
<script type="text/javascript">
js_var="<?php echo $php_var; ?>";
alert(js_var);
</script>
';
}
$php_var = 'later changes';
?>
<script type="text/javascript">
var js_var;
</script>
This doesn't work, however. js_var is set when the inline script is run, but it is just set to a string that says <?php echo $php_var; ?> rather than actually evaluating it.
PHP runs first, and whatever JS is sent to the browser is run. I think you just want this:
echo '<script type="text/javascript">
js_var = '.json_encode($php_var).';
alert(js_var);
</script>';
$php_var = "foo";
echo '
<script>
var js_var = '. json_encode($php_var) .';
alert(js_var);
</script>
';
Produces:
<script>
var js_var = "foo";
alert(js_var);
</script>
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';
Is there anyway I can use a php variable in the JQuery script?
Example:
PHP variable: $sr2
Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')
How can I make it so the variable is valid in that JQuery part?
Thanks
PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.
<script type="text/javascript">
var my_php_var = <?php echo json_encode($the_php_var) ?>;
</script>
or retrieve the value via an AJAX call, which means you're basically creating a webservice.
What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.
<script type="text/javascript">
<?php
$phpVar = "foo";
echo "var phpVariable = '{$phpVar}';";
?>
</script>
Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -
<script type="text/javascript">
var phpVariable = 'foo';
</script>
Now your phpVariable is available to your JavaScript! So you use it like you would in any other case -
$("div."+phpVariable);
That will retrieve us any <div> element with a foo class -
<div class="foo"></div>
Assuming your jQuery is in the same file:
... $('#a2_bottom_<?php echo $sr2 ?>') ...
You could output it as part of the page in a script tag... i.e.
<script type="text/javascript">
<?php
echo "var sr2 = \"" . $sr2 . "\"";
?>
</script>
Then your jQuery line would be able to access it:
$('#a2_bottom_' + sr2)
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");
is it possible to achive similiar results in JavaScript ? My aim is to not write static html within string literals.
<?php
if (someCondition) {
?>
I'm here, because PHP allows it.
<?php
}
?>
For example:
<script>
if (someCondition) {
</script>
I'm here, because JavaScript allows it.
<script>
}
</script>
I am aware of the following solution:
<p id = "variable">I'm here, because JavaScript allows it.</p>
<script>
var p = document.getElementById('variable');
if (!someCondition) {
p.parentNode.removeChild(p);
}
</script>
Nice thought, but it's not possible in the way you want it.
Every <script> element is evaluated as a JavaScript independent program, which will throw a syntax error in your case.
You'll have to generate the <p> element inside of your JavaScript.