mix javascript and php - php

I have a file called: file.php
contained in this file is the following code:
<script type="text/javascript">
//....
var sumJS = 10;
<?php $sumPHP = sumJS ?>
</script>
<?php echo "Sum = " . $sumPHP ?>
How can I assign sumJS for $sumPHP?
If I would like to make this conversely then I would write:
$sumPHP = 10;
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
But how can I re-make this for my problem?

Javascript can change the variables of PHP and vice versa.
Here is an example of that.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php $aphp=1 ?>
<script "text/javascript">document.write("<?php $aphp=2 ?>")
var ajava=1;</script>
<?php echo "aphp= $aphp"; echo "<br>";
echo "<script \"text/javascript\">ajava=2;</script>"
?>
<script "text/javascript">document.write("ajava= "); document.write(ajava)</script>
</body>
</html>
What if I want to assign a php variable to a java variable and vice versa
The above showed that you can assign values to java in php and vice versa by simply writing out an assignment using echo in php and document.write in java. That is how you assign a value.
Mixing actual variables between php and java is not much more complicated. What you do is write an assignment in the language you need to get the value of a variable from and assign it to a variable in the other language. Here is an example of that.
Assign php to java
<?php echo "<script type='text/javascript'>javasum=$phpsum</script>" ?>
assign java to php can be done in two ways
<script type='text/javascript'>var str="<?php $phpsum=";
str=str+javasum; str=str+" ?>";
document.write(str);
</script>
or more conveniently
javasum=<?php echo $phpsum ?>;
Mixing php and javascript to do things other than variable assignments
Javascript can also be mixed in the phpcode to do a javascript function in the phpcode. Say you wanted to use javascript to highlight text only if a condition is met in the php code. But to do this you need to echo the javascript code section. Also use the escape character, \' to include quotes in a echo command. Here is an example of this
Before you get started be sure php content type is in html. In dreamweaver site editor software, a header to do this is automatically included.
<p><span id="htext">htext</span></p>
<?php
$a=5;
echo "<h3> hello world</h3>";
if ($a==5) {
echo "<script type=\"text/javascript\">";
echo "document.getElementById(\"htext\").style=\"background-color:yellow\"";
echo "</script>";
}
?>
<p>is a=5</p>
<p><?php echo $a ?> </p>

$sumPHP is a server-side value, which will be evaluated on the server. Then the server generates page content and sent it to the client. Then browsers receive the page content and evaluate client-side value sumJS.
So you can never assign sumJS for $sumPHP because $sumPHP is calculated before sumJS.
But can do this to show the page:
<?php echo "Sum = "?><script type="text/javascript">document.write(sumJS);</script>
or rather
<script type="text/javascript">document.write('Sum = ' + sumJS);</script>

You're just missing tags
<?php
$sumPHP = 10;
?>
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
demo

Sorry that at the moment I do not have the time to write an example. But I believe that this idea will work. Maybe someone here can do a quick test.
Just create a hidden element with a unique id, say a
span with id="uniqueBufferForCommunicatingBetweenPHPandJS" and style="display:none".
Then, with the JS part of the code, write the result into this span by using
document.getElementById("uniqueBufferForCommunicationBetweenPHPandJS").innerHTML = XXX;
You can even write XXX in the form of JSON.
Afterwards, you can use something in PHP like
$bufferspan = $dom->getElementById('uniqueBufferForCommunicationBetweenPHPandJS');
to get the span, and read its content, probably by using
$avariable = $dom->ownerDocument->saveHTML($avariable);
and then interpret the result stored in $avariable. I am not totally sure about the last PHP code.

Related

Call PHP variable in HTML

I wrote a code involving nested PHP and HTML parts as below. Why variable "v" is not displayed, But the variable "u" is?
<?php
$v= rand (1,15);
$u= rand (1,15);
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
<?php echo $v ?>
</body>
</html>
EOD;
echo $h;
?>
<html>
<body>
u=<?php echo $u ?>
</body>
</html>
PHP has two modes.
Inside <?php...?> (and other PHP tags) PHP code is evaluated
Outside those tags, code is streamed directly to the output
You have <?php echo $v ?> inside a PHP section (inside a string created with HEREDOC).
It doesn't trigger PHP evaluation of the content when the string is created because it is just part of the string. It doesn't trigger PHP evaluation when you later echo it because you are just echoing a string.
<?php echo $v ?> will be in the (invalid) HTML sent to the browser, and the browser will treat it as an unknown tag. The value of $v will be one of the attributes. The browser won't render anything for this unknown tab, but you will be able to see it in the Developer Tools Inspector or with View➝Source
Rethink your application design. Don't try to store strings containing PHP code. Generate the string with the data you need in it in the first place.
$h = <<<EOD
<!DOCTYPE html>
<html>
<body>
<p style="margin-top:80px">This is a random number:</p>
$v
</body>
</html>
EOD;
echo $h;

How can I access a variable in one block of PHP code in another block of PHP code in the same file?

I have something like this:
PHP code at the start:
<?php
$variable="example";
?>
Then HTML code:
<html>
<head>
<title>Title</title>
</head>
<body>
Then again PHP:
<?php
// code comes here, and I want to access variable $variable here.
?>
And then HTML code ends:
</body>
</html>
Is it possible to do this somehow? I don't want to create another file; I need to do this in this file.
Not Required unless if you are accessing it under functions ( as it will lose their scope)
test1.php
<?php
$var = 1;
//.. your code...
?>
<html>.....
<?php
echo $var; // prints 1
whereas the below code won't work...
<?php
$var = 1;
function displayVar()
{
echo $var; // You will get a notice .. !
}
Just do what you stated above and it will work.
<?php
$variable = 'Hello';
?>
<html>
<head>
</head>
<body>
<?php echo $variable; ?>
</body>
</html>
The above example will display a simple webpage with 'Hello' as the content. This is one of best strength of PHP actually.
try this
echo ($variable);
or
print($variable);
If it is the same file, yes it is possible, unless the variable is in a function. But this is a very simple question, that you could have tested yourself.

How to automatically reload page after a certain time based on a php variable

I currently have a php file that automatically plays the song at the top of a playlist. I have a $duration value that I pull from a mysql database and I want the page to automatically refresh after the song is finished playing.
The song is currently played within an iframe so this is the only way to tell that the song has approximately finished.
I've tried doing this in javascript but I'm having issues trying to pass a variable to the timeout period.
<script type="text/JavaScript">
function timedRefresh(timeoutPeriod{
setTimeout("location.reload(true);",timeoutPeriod);
}
</script>
<body onload="JavaScript:timedRefresh($x);">
...
</body>
It is simply a straightforward PHP variable output into the source:
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod){
setTimeout("location.reload(true);",<?php echo $song_duration_in_milliseconds; ?>);
}
</script>
Or use meta-refresh as pointed out in #Matt Clark's answer.
You can also use a META tag for refresh.
In PHP:
<?php
$Refresh = 600;
?>
And in your HTML head you can modify a META Tag:
<meta http-equiv="refresh" content="<?= $Refresh ?>">
Or as stated by Amadan you can just use the PHP to specify the meta tag in your PHP:
header("Refresh: " . $Refresh);
Or In Javascript:
<script type="text/JavaScript">
setTimeout("location.reload(true);",<?= $Refresh ?>);
</script>
Side Notes
The short tags:
<?= $Variable, $Variable2 ?>
Are the equivalent of using:
<?php echo $Variable; echo $Variable2; ?>

Interesting output in a simple PHP webpage

Here is a very simple PHP page with one javascript function in it. I am seeing the output differently. I am not able to understand why is it behaving that way.
In the code below, x echoes as 012012, but when I pass it into a javascript function and display it in an innerHTML, it displays differently as 5130 ??!!
Can anyone help ?
<?php
$x= date("mY");
echo $x;
?>
<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body <?php echo "onload='myfunc1(".$x.")'>";?>
<div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output
012012<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body onload='myfunc1(012012)'> <div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output (screenshot)
Because a number prefixed with a 0 is treated as octal by javascript.
This is happening because 012012 is being treated as an int. But, since it starts with 0, JavaScript treats it as base 8 (octal), and therefore converts it to 5130.
You need to wrap 012012 in quotes, so JavaScript treats it as a string. Also, I suggest only using PHP to echo the value you need, not the entire function call. Makes it slightly easier to debug.
<body onload="myfunc1('<?php echo $x;?>')">
Use Smarty, is a framework template PHP!
PHP code:
<?php
$foo = date('Y');
?>
Simple Print PHP Code
<body onload="myFunctionJS('<?php echo $foo;?>')">
Simple Tags PHP(It is not recommended)
<body onload="myFunctionJS('<?=$foo;?>')">
USE SMARTY TEMPLATE FRAMEWORK
Smarty Template Framework(PHP Code):
<?php
$smarty = new Smarty;
$var = date('Y');
$smarty->assign( 'foo' , $var );
?>
Smarty Template Framework(Template Code):
<body onload="myFunctionJS('{$foo}')">
<body <?php echo "onload='myfunc1(".$x.")'>";?>
should be
<body <?php echo "onload='myfunc1(".$x.")'>";?>>
The body tag is not closed

It is possible to include Php variables or URL in Javascript in an If-statement?

I want to make some thing like this
my-php-file.php
$lang = 'es';
my-js-file.js
if ($lang == es)
{
something-magical-happens;
}
or like this:
if (URL == www.mydomain.com/index.php?lang=es)
{
something-magical-happens;
}
you could generate js on-the-fly
my.js.php:
<?php echo "//Yes." ?>
var i = "<?php echo $_GET['lang']; ?>";
function doSomethingWithI(){
alert(i);
}
Now, try to include
<script type="text/javascript" src="my.js.php?lang=es"></script>
in your html and you'll see :)
Edit: Check it in action here: http://h.kissyour.net/so/phpjs/
Edit: Edited example on my server to closer resemble what I wrote here.
Edit: Oh yes. Don't forget to clean your code!
In this specific case, why not simply properly set the document language and then look at that using JavaScript?
<html lang="es">
And in the script:
if (document.documentElement.getAttribute('lang') === 'es') { alert('Spanish'); }
You can – as the accepted answer indicates – generate entire javascript files with PHP. But if you are just trying to access some limited dynamic content, this is often overkill. If you are just trying to access a few variables that need to be PHP generated, inline javascript works fine. Add this to your HTML's head:
<script type="text/javascript">
<?php if( $condition == true ) : ?>
var variable1 = <?php $var1 ?>,
variable2 = <?php $var2 ?>;
<?php else: ?>
var variable1 = <?php $var1Alt ?>,
variable2 = <?php $var2Alt ?>;
<?php endif; ?>
</script>
Just make sure you add this before any linked scripts depend on these variables.

Categories