Accessing php variables from javascript in Symfony2 - php

I am developing a small drawing tool which collects some data from the user before starting the tool. I'm using Symfony2 - the drawing tool is pure javascript.
So once the user reaches the page where the tool loads, javascript needs to know about some of the data the user has entered previously (for example height & width of the canvas), which have been sent to the controller by forms. I have no problem using the variables in the templates, but can't access them with the javascript files.
Is there a way to set javascript variables in a template?
I've included the javascript file in the template like so (which works):
<script type="text/javascript" src="<?php echo $view['assets']->getUrl('bundles/mybundle/js/myjs.js') ?></script>

Just put some script tags in your template and output the variable into them using PHP. It could look similar to this:
<script type="text/javascript">
var canvasHeight = <?php echo $canvasHeight; ?>;
var canvasWidth = <?php echo $canvasWidth; ?>;
</script>

Can't you just print the variable with php in the page? something like
<script type="text/javascript">
var t=<?php echo $var; ?>
</script>

Related

assigning js value to php

so I have this in my HTML file
<script type="text/javascript" src="load.js"> </script>
<script type="text/javascript" src="load2.php"> </script>
Saw somewhere you could call an external php file using the js script tag and whatever js in the php file would be rendered first.
But my problem is, I can't assign no JS variable from load.js to a php variable in load2.php but, however, I could alert using echo "alert(js variable);"; So that tells me it finds the variable and I could use it, but I can't assign it to a php variable :/ any help please?
When working between JavaScript and php you must remember one is client side (JavaScript) and the other server side (php). Therefore php can insert values into javascript before it is sent to the client and then rendered (processed). Although the reverse cannot happen as the "scope" of JavaScript is on the clients computer.
The way around this is to use AJAX requests from the client back to the server sending back the data / variable values you need.
JQuery provides an easy to use library with AJAX functionality.
Please see http://api.jquery.com/jQuery.ajax/
PHP is server-side, JS is client side. This means the PHP will run far before the JS ever gets assigned. The only way a PHP file is going to get a JS variable is if you post it using Ajax
One option would be to dynamically load the PHP-generated script and pass some GET parameters to the PHP. This would still require ajax, but could be done cleanly with jQuery. If you go with jQuery, this is the documentation for getScript.
EDIT
So, your HTML file should look like this:
<!-- your first javascript file -->
<script type="text/javascript" src="load.js"></script>
<!-- load jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript>
// get the variable from your first javascript file
// via a getter function or global variable
var x = getVarFromFirstFile();
// this will load your second 'javascript' (generated by php) file
// and will pass the variable 'x' as a GET parameter to the php
$.getScript("load2.php?x="+x);
</script>
Then the php in load2.php could access the variable x (originally from load.js) like this:
<?php
$x = $_GET['x'];
...

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

Passing a PHP Variable in external JS file [duplicate]

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.

Access PHP var from external javascript file

I can access a PHP var with Javascript like this:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>
But what if I want to use an external JS file:
<script type="text/javascript" src="externaljs.js"></script>
externaljs.js:
alert("color: " + "<?php echo $color; ?>");
You don't really access it, you insert it into the javascript code when you serve the page.
However if your other javascript isn't from an external source you can do something like:
<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>
and then in the file.js use color like so:
alert("color: " + color);
You can also access data from php script in Javascript (I'll use jQuery here) like this
Create input hidden field within you php file like this
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}
This will do the job as well :)
What I've seen done is let .js files run through the php interpreter. Which I can not recommend.
What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.
First of all you have to understand that no program can actually have access to the other program's variable.
When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well
What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa
Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.
It helps to have some understanding of taint checking, data verification, and security ;)
As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.
e.g. <div id='apple' class='red'> is completely available to javascript
Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:
PHP:
<?php
$my_php_array = [];
?>
HTML:
<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>
Javasript: (You can now use the array like a normal Javascript array)
my_js_array[0]
my_js_array.length
externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.
Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).
<script type="text/javascript" src="externaljs.js"></script>
You could change it to
<script type="text/javascript" src="externaljs.php"></script>
And the PHP script could just write JavaScript like that :
<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...
Though using AJAX like said Sepehr Lajevardi would be much cleaner
2017-2018 and above solution:
Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encode and json_encode yet, you could even send PHP Array variables like that:
index.php
<?php
$string = "hello";
$array = ['hi', 'how', 'are', 'you'];
$array = base64_encode(json_encode($array));
Then you could just load your desired js file with the parameter for a query string like this:
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
Then js/main.php will look like this for example. You can test your variables this way:
js/main.php
<?php
if ($_GET['string']) {
$a = $_GET['string'];
}
if ($_GET['array']) {
$b = $_GET['array'];
}
$b = json_decode(base64_decode($b));
echo 'alert("String $a: + '.$a.'");';
echo 'alert("First key of Array $array: + '.$b[0].'");';
exit();
?>
The following will then output when you open your index.php. So you see, you don't open js/main.php and you still got the javascript functionality from it.
You can include() them just as you would anything else:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
<?php include('/path/to/your/externaljs.js'); ?>
</script>
This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.
You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js

How to use Code Igniter to show Dynamic images via javascript(jQuery)

You can use the URL helper in Code Igniter to load CSS and Javascript with the base_url() method, but what if you have images dynamically being placed into your HTML via javascript? for example in my javascript file I've got
var arrowimages={down:['downarrowclass', 'images/down.png', 23], right:['rightarrowclass', 'images/right.png']}
and those images will be placed into whatever menu item I've specified has a drop down menu.
but that file is a .js file so obviously the server won't load php inside of it.
so, how can I set the base url for the JS?
Thanks!
-Aaron
Define a constant javascript variable like BASE_URI in the of your view, you can then reference this variable in any of your external javascript files.
<head>
....
<script type="text/javascript">
var BASE_URI = "<?php echo base_url(); ?>";
</script>
....
</head>
External js...
var arrowimages={down:['downarrowclass', BASE_URI+'images/down.png', 23], right:['rightarrowclass', BASE_URI+'images/right.png']}

Categories