This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I'm tring to pass a session variable to javascript but not have success.
Searching stackoverflow i have found this discussion:
Passing Session variables to javascript
in my custom.js i have on header
<?php session_start(); ?>
.. /// js code
strActionPage = CurrentPath + "upload_file.php?ation=store&session_user_id=<?php echo $_SESSION['session_user_id']; ?> "; //the ActionPage's file path
but i cant get session variable from upload_file.php page
where do I wrong?
Tks to all
Wait, you're using PHP on a JavaScript file (that's what your OP says)? Not gonna work. You're going to have to pass it to a JavaScript function as a parameter like so:
<?php
session_start();
// HTML and stuff
<script type="text/javascript" src="custom.js"></script>
<script type="text/javascript">
passSession("<? echo $_SESSION['session_user_id']; ?>");
</script>
It's hard to say without knowing more about your particular error, but I did notice what seems like a typo in the code you posted:
strActionPage = CurrentPath + "upload_file.php?ation=store&session_user_id=<?php echo $_SESSION['session_user_id']; ?> "; //the ActionPage's file path
You have ation-store -- did you mean to write action=store?
This is how I might do.
<script type="text/javascript">
var user_id=<?php echo $_SESSION['session_user_id']; ?>;
strActionPage = CurrentPath + "upload_file.php?action=store&session_user_id="+user_id;
</script>
There is also a possible mistake. You are using "ation" . Should that be 'action'?
Related
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.
This question already has an answer here:
Pass Javascript var into PHP var
(1 answer)
Closed 9 years ago.
Is this how you would pass a var from JS to PHP? or is there a better solution. Please could you help with the easiest and most efficient way.
<!DOCTYPE html>
<html>
<body>
<script>
var name="John Doe";
document.write(name + "<br>");
</script>
<?php
$name = <script>document.write(name);</script>
?>
</body>
</html>
I know this won't work, but how would I do it?
<?php
$name = <script>document.write(name);</script>
?>
You can not do this
As php is a server side language and js client side,
First it run in server then it output to client were it executes js. So you can not pass values from js to php like in the code above.
If you want to do that you need to use AJAX.
please try this:
<?php
echo "<script language=\"javascript\">
var name=\"John Doe\";
document.write(name + \"<br>\");
</script>";
?>
i hope this would be useful
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I got a html5 upload script from
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
can i pass php variable to js?
in this html5 upload script
the script.js call the post_file.php to upload file
in post_file.php
$rand = time();
i set the rand is the filename
for example uploaded filename: 1331956640.jpg
can i pass this $rand to script.js?
because i can't print the result in php, only can print something in script.js
this is the html5 upload script download link from tutorialzine
enter link description here
sorry my english not good, thank
<script>
var my_javascript_var = <?php echo $rand; ?>
</script>
or
<input id="my_rand_value" type="hidden" value="<?php echo $rand;?>" />
in js do so
var my_javascript_var = $("#my_rand_value").val():
It's not actually about "passing" a variable from PHP to JavaScript.
Remember that PHP is a server-side scripting language, and JavaScript resides on a client's browser.
So, you could actually... write directly any javascript you wish from your PHP script.
Let's say, you've got a $a variable... then you could simply enter it in your javascript code like this :
<script type='text/javascript'>
var a = <?php echo $a; ?>
</script>
However :
If what you mean is to actually use the $a var while the page has loaded, or retrieve the result in some way, WITHOUT reloading, then what you probably need is Ajax.
To use AJAX, I would either suggest :
the jQuery load method
using some ready-made AJAX object
You can do this
<script>
var javascriptvar = <?=$rand ?>
</script>
You dont need to ....
<script>
var rand = new Date().getTime();
</script>
this uses only JavaScript to get the same result
You can do it this way:
<script language="javascript" type="text/javascript" src="your.js"></script>
...
<img src="your_button.gif" />
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)
I'm working on a project and it's already done, but it needs one more midification and its applying language constants in javascript files.
consider we include a javascript file and in that we have something like this
alert("YOU Have VOTED BEFORE");
easy like that , the script will alert that text
but what if we need to alert a language constant of it :
alert("<?php echo _VOTED_BEFORE?>");
this will be worked only if echo the script like inline of my php codes ...
but, how can we read and include php constants or $vars for a outside JavaScript file ???
For a cleaner structure, I think the best way is to set all the data you get from PHP in one place, i.e. in the HTML you serve via PHP:
<script>
var MyNameSpace = {
config:
something: "<?php echo _VOTED_BEFORE ?>"
}
}
</script>
In the JavaScript file you include afterwards, you can access the value via MyNameSpace.config.something.
This makes it also easier to reuse the message.
There is a way of doing this using a query string in the script path
See my answer here
How to pass variable from php template to javascript
Unfortunately this will break the cache for your js file so weight your options first
<script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script>
for the sake of not writing too much code refer to the link to see how to retrieve the value
Actually, what you had was close to being proper.
<?php
// Valid constant names
define("VOTED_BEFORE", "false");
?>
<script type="text/javascript">
alert("<?php echo VOTED_BEFORE;?>");
</script>
If it's not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in your external js files then declare it as a global in your PHP
file before you reference the external js.
<script type="text/javascript">
var globalvar = '<?php echo _VOTED_BEFORE ?>' ;
</script>
<script type="text/javascript" src="externalfile.js"></script>
Though it's not always a good idea to clutter the global namespace.
You can use cookies to save these constants and read them in via JavaScript or you will have to use AJAX
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.