This question already has answers here:
Efficient way to Pass variables from PHP to JavaScript [duplicate]
(8 answers)
Closed 9 years ago.
What is the best way to pass a server-side PHP variable to Javascript?
To simplify the problem assume that we have a variable in PHP ($phpVar) and we want to assign its value to a Javascript variable (jsVar)
Javascript files are loaded in html - they are not created dynamic!
Some food for thought:
1. Print with PHP before loading Javascript files:
<script language="javascript" type="text/javascript">
var jsVar= <?php echo $phpVar?>;
</script>
2. Store in DOM (in hidden elements)
a. in PHP:
<span data-name="phpVar" data-value="<?php echo $phpVar?>"></span>
b. Read in Javascript files (assuming jQuery available):
var jsVar= $('span[data-name="phpVar"]').attr('data-value');
3. Ask it with AJAX after page has loaded
Obviosly not the best solution. Doesn't fit to all scenarios and requires an additional request...
In conclusion:
They both seem ugly to me... Is there a better approach?
Is there any frameworks that can handle this dependecies? Please keep server reconfiguration minimal.
The best approach would be providing an "internal API" requested via AJAX from client side.
Doing this way you can keep your sides separated.
After this, the fastest way is printing in a shared file the values you want to share (as you wrote in your question).
As a last note: if you carry on with the second way I would suggest you
json_encode()
as a really helpful method to pass arrays and objects from php to javascript.
So if you have your php array:
$array = array( "a" => 1, "b" => 2 );
<script language="javascript" type="text/javascript">
var js_array= <?php echo json_encode( $array ) ; ?>;
</script>
It depends on the situation, but in common, predominantly to use first case. But don't forget about quotes if you pass a string:
<script language="javascript" type="text/javascript">
var jsVar = '<?php echo $phpVar?>';
</script>
Related
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 7 years ago.
I am currently looking for a way on how can I access a javascript variable and use it in my php script (same page). I heard about using ajax, but I don't really know where to start, I have little experience when using ajax, could someone please help me start with this problem? The code below is just an example on what I am trying to do:
<script>
var fruit = "apple";
</script>
I am trying to get the value of the variable fruit for example using a php script
<?php
$fruit = code to get the value maybe....
?>
My example above must be wrong and I know ajax is the way to go, but could someone please help me on how to approach or start with it? I would appreciate it! Thanks!
in the js you use ajax through jquery to send the vars to php
var fruit = "apple";
$.get('server.php',{fruit:fruit});
in server.php
$fruit = $_GET['fruit'];
of course opening server.php directly will cause an error, you have to run the javascript code in the browser, use the developer tools to inspect the request and the php file output.
Even better you can get back the server.php output in javascript like this:
var fruit = "apple";
$.get('server.php',{fruit:fruit})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
This question already has answers here:
PHP loop; how to print each result and delay it for a second before echoing another result?
(2 answers)
Closed 8 years ago.
I have something like this
<?php
for ($x=0; $x<10; $x++) {
echo $x;
}
?>
Now i need to display that $x data one after another with one second delay; i believe i need javascript to do that.
I've found various of similar scripts, but none worked for me, can anyone post any example on how to do that?
Thanks in advance
Yes, you'll need JavaScript for this. All PHP can do is emit the values to client-side code. Then it's up to the client-side code to display those values.
So, for example, your PHP code can populate a JavaScript array:
<script type="text/javaScript">
var values = <?php echo json_encode($php_variable); ?>;
</script>
In this case $php_variable would be an array containing the values you want to display. Now your client-side code has an array called values which it can iterate. You can use setTimeout to schedule something to happen with a delay. Iterating over that array, it might look something like this:
var index = 0;
var displayValue = function () {
if (index >= values.length) { return; }
var value = values[index++];
// display "value" somewhere on your page
setTimeout(displayValue, 1000);
};
displayValue();
This should display each value in the array with 1-second increments. Note that I sort of glazed over the "display somewhere on your page" part, since that's up to you really. Where/how are you looking to display this? This works a little differently client-side than it does server-side, since the entire HTML document is already rendered. You need to identify where in that document you want to display the value and display it there, not just "echo" it.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
I have some php $_SESSION vars that I am using in my site. like follows
$_SESSION[$select_grid_name."_id"];
The grid name is a name of the table been targeted. This all seems to work well but I have one issue that now I am trying to get the session var on a javascript call which is generated programatically for all grids
I want to do something like this
var grid_name = sender["id"]; //id assigned form grid call on select
var field_id = "<?php echo $_SESSION[?>" +grid_name +"]; ?>";
this errors because I am breaking up the php echo call. How can I call the php session var based on the javascript grid name?
You simply cannot do that.
Client side (JavaScript) variables are not sent to the server like that.
If you want PHP to be aware of variables set in JavaScript, you should look into making an AJAX request. Popular libs like jQuery will make easy work of this for you.
try this
in html
<input type="hidden" id="<?php echo $select_grid_name; ?>" value="<?php echo $_SESSION[$select_grid_name."_id"];?>"/>
in jquery
var grid_name = sender["id"];
var field_id = $("#"+grid_name).val();
Try this :
var grid_name = <?php echo sender["id"]?>
Currently I am using this small php script to eval the javascript on a page.
EDIT
Note: this is working, I just want to avoid using php to change part of the javascript
<script type="text/javascript">
<?php
include 'n1.inc';
if (isset($_GET['resultado']))
{
if($_GET["resultado"] != null){
echo $_GET['resultado'];
}
}
include 'n2.inc';
?>
</script>
I know that it is possible to read the querystring with only javascript as it was already demonstrated in the following questions:
How can I get query string values in JavaScript?
JavaScript query string
I have tried with:
<script src="n1.js"></script>
<script> eval(someQueryStringFunction()); </script>
<script src="n2.js"></script>
it gives an error as the values on the querystring should be in the middle of the function.
If you want to look at the n1.js and n2.js feel free to look at https://github.com/kyllopardiun/MapaColoracao
Passing javascript in a query string will simply not work atall. Javascript will contain characters that are not allowed in a querystring.
As mentioned above requirejs will allow you to embed javascript files into the page DOM.
eval is quite a serious security risk and not recomended for security reason. There's plenty of articles on why eval is evil.
I have got the following code:
<HTML>
<?php
if(isset($_GET['adjust'])){
$adjust = true;
}
//More variabele declaring
?>
<HEAD>
<script type="text/javascript">
var adjust = "<?php Print($adjust); ?>";
//More variable 'transports'
</script>
</HEAD>
<!-- rest of the file -->
I would like to clean this up a little, because I have a serious amount of variables. This troubles the readability and overview of the file.
I thought of putting it all into an external JavaScript file, but it didn't seem to work.
<HTML>
<?php
if(isset($_GET['adjust'])){
$adjust = true;
}
//More variabele declaring
?>
<HEAD>
<script type="text/javascript" src="externalJS.js"></script>
</HEAD>
<!-- rest of the file -->
With externalJS.js:
var adjust = "<?php Print($adjust); ?>";
//More variable 'transports'
According to this question, also asked here on stackoverflow, this ain't possible.
Is there a way to do it with the knowledge of the past few years, since above question was answered?
Are there other alternatives to improve the readability?
P.S.: I think it is worth mentioning I gain my php-variables from the url, txt-files and cookies.
When I have had cases where I have had to place a number of variables into javascript, I have used the approach of loading all those items into an object (or array) and outputting that data into an object/array literal in javascript.
For example:
<?php
$js_object = new stdClass();
$js_object->foo = 'some value';
$js_object->bar = 'some other value';
?>
<script type="text/javacript">;
var php_values = <?php echo json_encode($js_object); ?>;
console.log(php_values.foo);
console.log(php_values.bar);
</script>
This does a few things.
Your JS output section does not need to change at all if the variables being passed need to change. Anything you want to access in JS just needs to be loaded in $js_object before the object is output to the browser via json_encode()
It puts all your PHP-provided values in a neat object/array in javascript where they can be accessed.
You can easily pass complex data structures in this manner (nested arrays, objects containing arrays, arrays of objects, etc.)
If needed you could extend the object in javascript to provide methods, etc. to act on the data.
I would also comment that you might want to think a bit about whether you wanted to pass cookie data in this manner. Cookie data is available to javascript anyway so you may want to work with that data directly if you need to change values or such.
Mike Brant's approach is good here (storing everything in a json object), but to accomplish specifically what you are asking here in a more segmented way you can simply make your included javascript library a PHP file that outputs Javascript headers. Your markup would look like this:
<HTML>
<?php
if(isset($_GET['adjust'])){
$adjust = true;
}
//More variabele declaring
?>
<HEAD>
<script type="text/javascript" src="externalJS.js.php?<?=http_build_query($_GET);?>"></script>
</HEAD>
<!-- rest of the file -->
And then your externalJS.js.php file would look like:
<?php
header("content-type: text/javascript");
?>
var adjust = "<?php Print($adjust); ?>";
//More variable 'transports' and any other PHP/Javascript code
The header here tells the browser to treat the result as javascript despite the .php extension.
Also, if you really wanted to you could also just tell you webserver to parse js files as PHP, so that it would look for <?php ... ?> segments and execute them, so you don't even need to have a non-js extension on the file:
AddType application/x-httpd-php .js
But be careful when you do this, as it means that all javascript files (or any files in the specified directory, if you're using htaccess) will be parsed, which could open up security holes if you're not careful.
A couple of side notes:
Have a look at the discussion around text/javascript vs application/javascript
Don't capitalize all the tag names. Yes, HTML5 says it's OK, but the W3C recommends lowercase as a convention (both for standardization and for any possible conversion to xhtml).
When just printing or echoing, first of all use lower-case (print vs Print), don't wrap the printed variable in parentheses (print and echo are language constructs, so they don't need the parentheses and there are situations where using them can cause problems), and lastly, if all you're doing in a PHP tag is printing or echoing, try using PHP echo shorthand (most webservers understand them by default): <?=$var_name;?> is the same as <?php print($var_name);?>
Create an array in PHP containing the variable name (as you want it in javascript) as the key for each element, and the value as you want it in javascript as the value of each element. Then, follow this:
$myVars = array();
$myVars['adjust'] = isset($_POST['adjust']) ? true : false;
$myVars['other'] = isset($_POST['other']) ? true : false;
$myVars['another'] = isset($_POST['another']) ? true : false;
<script type="text/javascript">
<?php
foreach( $myVars as $k => $v ):
echo 'var ' . $k . '="' . $v . '";';
?>
</script>
Cheers