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.
Related
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!
This question already has answers here:
What is the safest way of passing arguments from server-side PHP to client-side JavaScript [duplicate]
(5 answers)
Closed 9 years ago.
I have a file called english.php containing a tonne of variable values. All part of the $LANG array.
Examples:
$LANG['value_1']="abc";
$LANG['value_2']="xyz";
I then have a million different .php files that use require_once('english.php');
That is fine but I also have a lot of javascript and jquery plugins that I am using. They all have external .js files. How can I get the values of $LANG in javascript to it is usable in the .js files?
I guess I am gonna need to add code to the top of the .js to somehow reading the .php data before running the remainder of the javascript code. I just have absolutely no idea how to do that.
I have seen a few possible ideas but I don't really want to do a major rewrite of everything. Looking for a simple solution. Can anyone help this clueless novice?
======= Added more info based on comments received =======
I now have a lang.php with this code in it...
<?php
session_cache_limiter('nocache');
session_start();
require_once ($_SESSION['language'].'.php');
$js_out = json_encode($LANG);
?>
<script>
var LANG = <?php echo $js_out; ?>;
alert(LANG.value_1);
</script>
When I access the lang.php it successfully accesses english.php and alerts 'abc'
My problem is that this does not work when added to a different file...
<script type='text/javascript' src='lang.php'></script>
<script>
alert(LANG.value_1);
</script>
======= Edited to add the SOLUTION =======
Thanks to the comments of the people below, I got rid of the <script> in the lang.php file and it worked.
I now have a lang.php with this code in it...
<?php
session_cache_limiter('nocache');
session_start();
require_once ($_SESSION['language'].'.php');
$js_out = json_encode($LANG);
?>
var LANG = <?php echo $js_out; ?>;
You can have the following code inside english.php:
<?php
$LANG['value_1']="abc";
$LANG['value_2']="xyz";
$js_out = json_encode($LANG);
?>
<script>
var LANG = <?php echo $js_out; ?>;
</script>
LANG is then visible to your javascript after the page loads.
you can do that with a simple script tag in the files which need to see the $LANG in javascript.
1) Create a php file which echoes the javascript representation of $LANG - lets call it lang.php
it should do something like
echo 'var english ="' . $LANG['value_1'] "';";
2) include this file in your html and then u can use the variables english etc. as normal javascript variables.
<script language="javascript" src="http://whatever.com/lang.php"> </script>
Try:
<script ...>
var mydata = <?=json_encode($LANG)?>;
</script>
json_encode returns a string containing the JSON representation.
http://php.net/manual/en/function.json-encode.php
I think the right thing to do is something like :
var foo = "<? echo $LANG['bar']; ?>";
The less php code you write in a js code, the better and cleaner it is.
You can create a PHP file:
<?php
header('Content-Type: text/javascript');
echo 'var lang = {};';
foreach ($LANG as $key => $value) {
echo "lang['$key'] = '" . addslashes($value) . "';";
}
?>
then link the script and you can use the lang object:
<script type='text/javascript' src='/path/to/lang.php'></script>
<script type='text/javascript'>
alert(lang.value_1);
</script>
Remove the <script></script> tags which possibly cause syntax errors when linked as a text/javascript 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.
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; ?>
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I've read lots of thread on here but I am still unable to get a variable passed from PHP to an external JS file and wondered if someone could assist?
In my PHP file I have the following;
<script type="text/javascript">
var pass_this_variable = <?php $company['website']; ?>;
</script>
<script type="text/javascript" src="/js/track.js"></script>
In the JS file I have the following;
document.write('<IFRAME SRC="$company['website']" WIDTH="300" HEIGHT="400"></IFRAME>');
What I am trying to achieve is an IFRAME be opened and populated with what is contained within $company['website']. I know I can just use IFRAME directly in the PHP file, but this isn't what I have been tasked with for my homework. When I do use IFRAME directly in the PHP file it works fine, and if I specify a static URL in the JS file such as http://www.google.com this also works fine.
Can anyone assist? Thanks
EDIT:
Thanks for the answers so far, however I'm still unable to get it working :(
The frame that I have in track.php (or track.js) won't load the url thats specified in $company['website'], yet if I change it to http://www.google.com its working fine. For some reason the $company['website'] value isn't being passed :(
if you want your external javascript to be dynamic you can make it a php file and give the correct header, example:
<script type="text/javascript" src="/js/track.php"></script>
track.php
<?php
// javascript generator
Header("content-type: application/x-javascript");
?>
document.write('<IFRAME SRC="<?php echo $company['website'] ?>" WIDTH="300" HEIGHT="400"></IFRAME>');
PHP file (don't forget echo and quoting):
<script type="text/javascript">
var pass_this_variable = '<?php echo $company['website']; ?>';
</script>
<script type="text/javascript" src="/js/track.js"></script>
JS file (use pass_this_variable instead):
document.write('<IFRAME SRC="'+pass_this_variable+'" WIDTH="300" HEIGHT="400"></IFRAME>');
You should fix this line:
var pass_this_variable = <?php echo $company['website']; ?>;
Adding echo and it should work
JavaScript provides you the functionality of ajax for the purpose of reading the PHP or text files. Why don't you create the HTML iframe inside a PHP file with your variables parsed and then take back the response and "throw" it inside a div.
The code for your PHP file:
$cmp = $company['website'];
echo '<input type="hidden" id="cmp1" name="cmp1" value="' . $cmp . '" />';
The code for your JavaScript (.js) file to get the PHP file value:
var company = document.getElementById('cmp').value;
Call a PHP file inside the JavaScript source. You can find the tutorial here:
http://www.javascriptkit.com/javatutors/externalphp.shtml.
So your code will be like this:
<script type="text/javascript" src="track.php?company=<?php echo $company['website']; ?>"></script>
In the PHP file you can fetch the value through $_GET variable and use it in the iframe. Make sure to sanitize the input.