How to put php inside JavaScript? - php

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>";
?>

Related

echo in jquery doens't output as expected

I found on stackoverflow how to use a php variable in jquery, but on my test page, it simply isn't working:
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
The code above outputs "" literally in the box where I want it to say "test123". I tried using single quotes instead of double, other small changes ... Didn't get it to work. Am I missing something?
The code above sits in a .js file which is linked in a .php page, which is (again) linked in my index.php file via require_once.
You should not use PHP in javascript files (.js). Javascript and PHP are different languages. PHP works on the server-side and Javascript on the client-side.
You have to put this code in your <head> under the jquery.js file, like this:
<script type="text/javascript" src="link-to-jquery-file.js"></script>
<script type="text/javascript">
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
</script>
Also make sure your file extension ends with .php
There is also an advanced solution for this, and that would be using the header() function. Save as javascript.php or someting Example:
<?php
header("Content-Type: text/javascript");
?>
$('#q').keyup(function(e) {
var test = "<?php echo 'test123'; ?>";
alert(test);
});
Then attach the file in your <head> like this:
<script type="text/javascript" src="javascript.php"></script>
Goodluck!

Can I insert PHP and javascript code in the same HTML file?

<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.

PHP and JS within HTML

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.

How to get value from php javascript?

I have a file php javascript
in news.js
news_id = 1;
document.write('<div id="news-id"></div>');
function output(strHtml) {
document.getElementById('news-id').innerHTML = strHtml;
}
in news.php is using
<?php
$news_id =
?>
news_id
<?php
$str = '<p>This is id: </p>'.$news_id;
?>
output(<?php echo json_encode($str); ?>);
And index.html i call
<script src="news.js" type="text/javascript"></script>
<script src="news.php" type="text/javascript"></script>
When i run index.html is error, how to get news_id from js to using in php
Well, as wrong as the original question is, there is a way to get the a JS variable into a PHP file.
In the HTML:
<script src="news.js"></script>
<script>
document.write('<scr'+'ipt type="text/javascript" src="news.php?myvar='+myvar+'" ></scr'+'ipt>');
</script>
In news.js:
var myvar = "HELLO";
In news.php:
alert("<?php echo $_GET["myvar"]?>");
Again, I highly discourage this approach... but it works.
You can't call news.php like this. It should be included in the html file like this:
include("news.php");
and you should change the extension of your html file to .php
To use PHP as javascript source <script src="news.php"
you need explicit declare content-type in .php
<?php header("Content-type: text/javascript"); //at very first line no white-space before ?>
//this is javascript content..
Important!
first, PHP execute on web server and send response to client(browser).
then javascript execute later in web browser.
To use js value inside php function you need AJAX GET/POST.

Inserting PHP variable value in Javascript file

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; ?>

Categories