This is what I am trying to do:
I have a data.php page.
In this page I have mostly HTML. Within the HTML I have some PHP code, designated by
<?php
?>
Now, I am trying to insert JavaSript with in the PHP; something like below:
<?php
<script type="text/javascript">
</script>
?>
But I get 'syntax error' notification from Adobe Dreamweaver.
What am I doing wrong here?
Thanks for any help.
You need to end your PHP and then start the Javascript
<?php
...php here...
?>
<script type="text/javascript">
</script>
<?php
... more php ...
?>
You shouldn't enclose Javascript into <?php ... ?> tags.
PHP is executed on the server, before the request reaches the client. Javascript is executed on the client. Therefore you need PHP to echo the javascript.
<?php
echo '<script type="text/javascript" src="xxx">';
echo 'SOME JAVASCRIPT FUNCTIONALITY';
echo '</script>';
?>
Not that I recommend it
If you must enclose JavaScript within PHP tags then you can do something such as this:
<?php
echo '<script type="text/javascript">';
echo '</script>';
?>
Keep in mind that you may have to escape quotes if you need to use the same types within the echo statement. This can be done by adding a back slash - \".
I was recently involved on a project myself where we needed to do some encryption using PHP and use the values returned within the JavaScript but our code was in the following form:
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>
It can be a nightmare to maintain but it is better form than the first example in this answer.
Related
<HTML>
<script language="JavaScript">
<script language="php">
</script>
</script>
</HTML>
<HTML>
<script language="php">
</script>
<script language="JavaScript">
</script>
</HTML>
I want to insert PHP and javascript code in HTML code like above.
Can I do this work??
It doesn't work like that, you can have them in the same file per se, just not like you have.
PHP is executed on the server and the result is sent to the client, whereas the JS code is executed by the client's browser.
<?php
//php code in here is evaluated and the result sent to the client
$somevar = 1234;
?>
<HTML>
<script language="JavaScript">
//javascript in here is evaluated by the client
//you could insert PHP values here to be used in JS if you want
//make sure you escape them though...
var some_js_var = <?php echo $somevar; ?>
//the JS var above would contain the value of php variable $somevar
</script>
</HTML>
<HTML>
<script language="JavaScript">
<?php
// Your PHP code here that outputs javascript
?>
</script>
</HTML>
<HTML>
<?php
// Your PHP code here that outputs text/html code
?>
<script language="JavaScript">
</script>
</HTML>
But of course, as others pointed out, browser will not see your PHP code. It will be processed by the server and browser will see only the javascript/html.
sure, you can even make php generate javascript. php file is processed to html before sending it to client, and client will see nothing except html with javascript.
You can also insert your code like this, don't give error
<HTML>
<script language="JavaScript">
<script language="php">
echo "alert('javascript alert')";
</script>
</script>
</HTML>
<HTML>
<script language="php">
echo "php code runned";
</script>
<script language="JavaScript">
</script>
</HTML>
If you want php to be executed inside javascript, then you have to use AJAX.
AJAX is a javascript code that allows you to call the server, thus executing php code and returning the result to you, at any time you wish (not only at the creation time of the page, but at the time the javascript code is called).
https://www.w3schools.com/xml/ajax_intro.asp
with jquery is even easier:
https://api.jquery.com/jquery.ajax/
You can put PHP code in the middle of a fichero.js???
Many do not know, but not in principle. If the server to interpret a php file needs to see the php extension, note that you can not set or if the file is php html extension, therefore you're not a js file extension. What you can do is something like the php type="javaScript"> '; echo 'write ("'. $ name. '");'; echo ''; } ?> For example.
I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file.
I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?
Rather than try to mix PHP into javascript files, here's what I do in the HTML template:
<head>
<script>
var BASEURL = "<?php echo base_url(); ?>";
</script>
<script src="/path/to/my_script1.js"></script>
<script src="/path/to/my_script2.js"></script>
</head>
This sets the variable and allows all your embedded scripts to access it. base_url() would be replaced by whatever method you use to fetch the base url with PHP.
Suppose you have a JS file written on the fly by PHP; file1.php
<?php
header('Content-Type: application/javascript');
$var = $_GET['var1'];
echo "jsvar = ".$var.";";
?>
The client-side source code of file1.php?var1=10 will then be
jsvar=10;
There exists several ways:
Load the baseurl via AJAX, but maybe this is to slow, maybe you need it earlier.
let the javascript file running through the php parser. Then you could use inline echos.
The most convenient and easiest way, is to make a <script>var baseurl = '...';</script> in the html/php output of your page.
You will need to make your file a php file, not a js file. From there you can include any PHP tags in the file to work your dynamic magic. The key to make this whole thing work is in the headers, which you will need to set like so:
<?php
Header("content-type: application/x-javascript");
echo 'var js_var = ' . $php_var;
?>
alert (js_var);
This technique can be used to for CSS files as well.
Heredoc worked for me today:
<?php
echo <<<ANYNAME
<script LANGUAGE="JavaScript" type="text/javascript">
<!--
// code ...
var myLatlng = new google.maps.LatLng($lat, $lon);
// code cont. ...
//-->
</script>
ANYNAME;
?>
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
php variable in html no other way then: <?php echo $var; ?>
I've tried (but its not working):
<?php
$htmlString= 'testing';
?>
<html>
<body>
<script type="text/javascript">
var htmlString=<?php echo $htmlString; ?>;
alert(htmlString);
</script>
</body>
</html>
Here is the tutorial that I've used for that purpose:
Try this:
<?php $htmlString= 'testing'; ?>
<html>
<body>
<script type="text/javascript">
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>";
alert(htmlString);
</script>
</body>
</html>
When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.
Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.
You're missing quotes around your string:
...
var htmlString="<?php echo $htmlString; ?>";
...
All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:
<html>
<head>
<script>
function myFunction(){
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>
The only proper way to put server side data into generated javascript code:
<?php $jsString= 'testing'; ?>
<html>
<body>
<script type="text/javascript">
var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
alert(jsStringFromPhp);
</script>
</body>
</html>
With simple quotes the content of your variable is not escaped against HTML and javascript, so it is vulnerable by XSS attacks...
For similar reasons I recommend to use document.createTextNode() instead of setting the innerHTML. Ofc. it is slower, but more secure...
you need quotes around the string in javascript
var htmlString="<?php echo $htmlString; ?>";
As others have pointed out you need the quotes, but I just want to point out that there's a shorthand method of writing this same line of code
var htmlString="<?=$htmlString?>";
See you can leave out the "php echo" stuff and replace it with a simple "=".
Let's see both the options:
1.) Use PHP inside Javascript
<script>
<?php $temp = 'hello';?>
console.log('<?php echo $temp; ?>');
</script>
Note: File name should be in .php only.
2.) Use Javascript variable inside PHP
<script>
var res = "success";
</script>
<?php
echo "<script>document.writeln(res);</script>";
?>
I want to trigger javascript alert using PHP.
Is it possible
I want to use it in head section, for displaying it at load time.
<head>
<?php
$valid="valid";
if(!isset($valid))
echo "<script type=\"text/javascript\"> alert('Hi');</script>";
?>
</head>
EDIT
i want to display javascript alert() at load time after checking existance of session
Of course this is possible.
All you are doing is outputting JavaScript, it's all the same thing.
The only issue is that you are nesting <script> tags, which is an HTML error, so get rid of the tags in the echo string.
<script type="text/javascript">
<?php
$valid="valid";
if(!isset($valid))
echo "alert('Hi');";
?>
</script>
By the way, as i'm sure you already know, this specific code will ALWAYS echo the "alert('Hi');"
i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?