echo in jquery doens't output as expected - php

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!

Related

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

How to pass PHP session variable into Javascript/jQuery function?

I have a PHP page that loads a session variable:
$user_id = $_SESSION['USER_ID'];
Previously, I included my Javascript/jQuery within that page, and added <? echo $user_id; ?> to set the Javascript variable:
$(document).ready(function() {
$(".button").click(function() {
var user_id = <? echo $user_id; ?>
var dataString = 'user_id=' + user_id;
$.ajax({
type: "POST",
url: "../add_user.php",
data: dataString,
});
return false
});
});
However, I'd like to move my Javascript to a separate page and call the script from my PHP page:
<script src="add_user.js" type="text/javascript"></script>
If I do this, I can no longer user <? echo $user_id; ?>, so what is the best way to pass my PHP variable into the Javascript/jQuery function?
You can configure your webserver to treat .js files as PHP scripts, which would let you execute your PHP code from within the .js file.
However, if that's not acceptable, you can always do something like:
<script type="text/javascript">var user_id = <?php echo json_encode($user_id) ?>;</script>
<script type="text/javascript" src="add_user.js"></script>
to define the variable at your PHP script level, and then include the external .js as usual.
If $user_id is always numeric, then the json_encode() bit is overkill, but I've gotten into the habit of using that everywhere I'm generating JS code dynamically. Using json_encode guarantees you're inserting a syntactically correct JS snippet.
<script>
var user_id = <?php echo $user_id; ?>
</script>
<script src="add_user.js" type="text/javascript"></script>
Now you can use user_id in your add_user.js file. Also, I would advise against using PHP short tags.
You will still be able to reference your varible in your external js file
<script type="text/javascript">
var yourvar = <? echo $user_id; ?>;
</script>
<script src="add_user.js" type="text/javascript"></script>
Just start the session on the other side. Its is also more secured, considering that JS data may be corrupted, even deliberately and may be exploited (security).
After starting the session - read the value there.
Of course, this is valid for scripts on the same vhost.

Pass PHP output to jQuery

I have got this code
/* Popup for hot news */
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('text to be shown')
.dialog({
autoOpen: false,
title: 'Table'
});
This code is in my JavaScript files which are included by header.php.
How to pass PHP output to this function?
Inputing <?php echo($mydata)?> in .html('') above does not solve anything.
Any reason why this gives an error?
Thanks for helping!
First of all your code is having some problem, $ in php is a prefix of variable and $ in jQuery is a selection sign. You can view the html source(the output) on browser for debug.
I can think of three ways to do so:
(1)The way you have mentioned should work, see the code below
<?php $foo='hi'?>
<script>
alert("<?php echo $foo?>");
</script>
(2)Another way is to separate server side and client slide code clearly for better maintenance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<?php echo"<div id='foo' style='visibility:hidden;'>HI</div>"?>
<script>
alert($('#foo').text());
</script>
(3)The last way is by passing variable from the URL http://example.com/example.php#hi
<script>
var foo= location.href.split('#')[1];
alert(foo);
</script>
Adding <?php //code?> to your JS files do nothing because JS files are not executed by Apache. You can either use Ajax to request for data once your page loads (if the data doesn't need to be there at start) or you can add those PHP code blocks to your HTML code.
Using Ajax (goes in your JS file)
$(document).ready(function(){
var u = 'data.php';
var d = {};//data
$.get(u, d, function(data){
//got by data. lets invoke some methods here
});
});
Putting it in your HTML (goes in your HTML file)
var __DATA = '<?php //output some data I prepared earlier ?>';
//I'm using __ and capitol case to denote a global variable. Just personal preference
<script src='myjsfile.js' type='text/javascript'></script>
//the variable __DATA is available to your JS file and you can use it

How to put php inside JavaScript?

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

Categories