Efficient way to Pass variables from PHP to JavaScript [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
From time to time I have to pass some variables from PHP to JS script.
For now I did it like this:
var js-variable = "<?php echo $php-variable; ?>";
But this is very ugly and I can't hide my JS script in .js file because it has to be parsed by PHP. What is the best solution to handle this?

If you don't want to use PHP to generate your javascript (and don't mind the extra call to your webserver), use AJAX to fetch the data.
If you do want to use PHP, always encode with json_encode before outputting.
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Please use a rest/rpc api and pass json to your js.
This can be done in the following way if you are using jquery:
rest.php
<?php echo "{name:biplav}" ?>
Then From your js make a get call like this:
var js_var;
$.get("rest.php", function(data) {
js_var=data;
});
Thats the simplest example I can think of.

<?php
// filename: output-json.php
header('content-type:application/json;charset=utf-8');
printf('var foo = %s;', json_encode($foo, JSON_PRETTY_PRINT));
json_encode is a robust function that ensures the output is encoded and formatted as valid javascript / json. The content-type header tells the browser how to interpret the response.
If your response is truly JSON, such as:
{"foo": 5}
Then declare it as content-type:application/json;charset=utf-8. JSON is faster to parse, and has much less chance of being xss exploited when compared to javascript. But, if you need to use real javascript in the response, such as:
var obj = {foo: 5};
Then declare it as content-type:text/javascript;charset=utf-8
You can link to it like a file:
<script src="output-json.php"></script>
Alternatively, it can be convenient to embed the value directly in your html instead of making a separate http request. Do it like so:
<script>
<?php printf('var foo = %s;', json_encode($foo, JSON_HEX_TAG | JSON_PRETTY_PRINT)) ?>
</script>
Make sure to use JSON_HEX_TAG if embedding into your html via the <script> tag, otherwise you risk xss injection attacks. There's also other flags you may need to make use of for more security depending on the context you use it in: JSON_HEX_AMP, JSON_HEX_QUOT, JSON_HEX_APOS. Those flags make the response less human readable, but are generally good for security and compatibility, so you should probably just use them.
I really want to emphasize the importance of declaring the content type and possibly using the JSON_HEX_TAG flag, as they can both help mitigate xss injection.
Do not do this unless you wish to tempt an xss attack:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

In my opinion, if you need to pass a variable directly in your JS, probably your web application is not good designed.
So, I have two tips:
* Use JSON files for general configurations, like /js/conf/userprefs.json
{
"avatar": "/img/users/123/avatar.jpg",
"preferred_color": "blue"
// ...
}
or (better way) you can retrieve your json confs with an AJAX call.
With PHP frameworks like Symfony2, you can decide a format in your routing configuration leaving the output of a variable to the template engine (like Twig).
I do an example for Symfony2 users but this can be used by any programmer:
routing.yml
userprefs:
pattern: /js/confs/userprefs.{_format}
defaults: { _controller: CoreBundle:JsonPrefs:User, _format: json }
requirements:
_format: json
_method: GET
Inside the controller you can do all the queries that you need to retrieve your variables putting these in the view:
Resources/Views/JsonPrefs/User.json
{
"avatar": "{{ user.avatar }}",
"preferred_color": "{{ user.preferred_color }}"
// ...
}
Inside your JS now you'll be able to retrieve the JSON with a simple AJAX call.
For performance purposes you can cache the JSONs (for example) with Varnish. In this way your server doesn't need to do a query every time you read the user preferences.

If you modify your .htaccess file to include
AddType application/x-httpd-php .js
you can use a .js file and it will be handled by PHP, which is half of what you require.
In terms of how ugly that solution is, I would say that this is the least ugly mechanism. You could try to pass your whole JS script through a PHP script as a string and do a search and replace for the variables you need to insert, but I think that you will agree that this is uglier than the solution you are currently using.

Put all your .js files in a folder and configure your HTTP server to redirect all the request to those files to a PHP file that loads the files and outputs them.
Let's suppose you have Apache and your .js files are in /js:
RewriteRule /js /getjs.php
getjs.php:
<?php
header('Content-Type: text/javascript');
include_once($_SERVER['SCRIPT_NAME']);
?>

As far as avoiding running .js files through the PHP parser, there is little you can do, except maybe fetching the value of js-variable via an AJAX call.
Also you may consider outputing the value like this:
var js_variable = <?php echo json_encode ($php_variable); ?>
to escape all the things that would break your javascript.

At the very least, you can use a PHP shortcode to make your "ugly" solution a bit cleaner:
var js-variable = "<?= $php-variable ?>";

Related

Sending php variables to Javascript variables

Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");

Calling PHP within Javascript results in literal string of function

I feel like i'm going round in circles here and missing something really daft...
My setup is essentially using CodeIgniter on the server-side, and Bootstrap on the client, but that's a little beside the point...
I'm trying to call a php value within a javascript function. The value is being stored in a protected variable within one of the php controllers, which is accessible by the views being loaded in that controller, as i'm accessing the variable directly in the html (and therefore I assumed i could access it in the javascript as well).
The code is here, it's really straight forward:
$(document).ready(function() {
var UID = "<?php echo $the_user->id; ?>";
console.log(UID);
});
I'm expecting this do do a console output of, say, "1", but it's actually outputting the actual string of "<?php echo $the_user->id; ?>". This will also happen if i'm just echoing a simple string, rather than a php variable.
I feel like this might be a config issue, but I really have no idea. If I remove the quotes from the php call, I get a
TypeError: can't wrap XML objects
console.log(<?php echo $the_user->id ?>);
Any ideas? I feel really dumb at this point :(
If you see <?php echo $the_user->id; ?> in the output, it means that your document is not parsed by PHP.
Check the file extension, check that it is indeed send to PHP in your webserver configuration.
For example if you add PHP tags in a .js file, it won't be passed to PHP, if you are using Apache, you would have to add:
AddType application/x-httpd-php .js
or set your variables in the HTML and send it as a parameter to the external Javascript.
mathieu-imbert is right about your file not being processed as a view. That's your first hurdle: make sure the page is being parsed.
Also, when trying to stick PHP variables into javascript, you have to think about escaping variables, dealing with unexpected values, etc.. Fortunately, there is an easy answer:
$(document).ready(function() {
var UID = <?php echo json_encode($the_user->id); ?>;
console.log(UID);
});
You can insert arbitrarily complex data into Javascript this way, provided you mind the usual restrictions with serializing PHP data.

Include javascript variable inside php tags

i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.

how to pass variable from php template to javascript [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 have a page where I want to display some points on map. I have small templates (like Smarty, but lighter) and there in template I have variable $points, that consists of coordinates of points I need. I need to pass them to javascript (because only javascript can render that map with points).
I have 3 variants of doing it. Can you tell, what is best?
1th way: (Template inserting javascript-tags with global variable)
tpl.php file:
<script>
MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
.js file
function renderMap(){
var points = MAP_POINTS; // using global. Is it really bad? or who cares? =))
}
2nd way: (Passing variable through the HTML element)
tpl.php.file
<input type="hidden"
value="<?php echo json_encode($this->points); ?>"
id="map_points_container">
.js file
function renderMap(){
// without globals, but needed to be parsed on local side
var points = $.parseJSON ( $( "#map_points_container" ).val() );
}
3rd way: (AJAX-way)
I don't pass $this->points from template file at all. I have another .php file that handles all my AJAX requests:
Ajaxing.php
function get_map_points($params){
// some operations
return json_encode ($map_points);
}
And than on local side I'll have something like this:
.js file
$.post ( 'ajaxing.php', params,
function(points){
renderMap(points);
}, 'json');
The third way is usual, but if I already pass some values from template to local page, then I can pass and map points too. In fact, I don't need to make another request for only this map points (that's why I don't like third way)
But may be you can advise me another way? a better way?
The way I choosed:
1th way with little remarks. All my 'map-rendering' code is in another file and it's like:
$(function(){
MAP_APP = {};
MAP_APP.some_prop = null; // some properties
MAP_APP.some_method = function(){}; // some methods
});
So in template file I only have to extend my MAP_APP object:
<script>
MAP_APP.points = <?php echo json_encode($this->points); ?>;
</script>
Yes, global variable. But it's like namespace of whole application.
Thanks to everybody.
The first way is definitely the least complicated and fastest.
The second one adds an additional processing step (the parseJSON()) that isn't necessary.
The third way is good if you're dealing with lots of data that is optional (i.e. is needed only if the user requests it, and it isn't 100% sure whether that will happen) or dynamic. It creates a new request though, and is not going to be immediately available.
If you don't want to use globals, you could e.g. wrap your JavaScript functions into an object, and populate an object property from PHP:
<script>
MyObject.MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
There is another funky way of passing variables in a js external file :)
Your PHP file:
<script type='text/javascript' src='script.js?id=0&some=<?php echo $whatever?>'></script>
and inside your script.js you can retrieve those values:
var scripts = document.getElementsByTagName('scripts');
// get your current script;
for (var i=0,l=scripts.length;i<l;i++){
if(scripts[i].src.indexOf('script.js') !== -1) { // or your script name
var query = scripts[i].src.substr(scripts[i].src.indexOf('?')+1);
// now you can split the query and access the values you want
....
}
}
The first one is most efficient and fastest. The second one is funky. The third one is also fine.
The first because it does not require any other requests. The second one is a bit odd, I would not use that kind of constructs, but that does not mean you can't. The third one is also fine, but you should think about if AJAX is the way to go. If you application requires multiple requests for points for different locations, then it might be the most efficient way to go.
I would go with your second method since you don't want to use AJAX for it (and it seems odd to use AJAX for something you already have in the current page). You want to limit the number of global variables in your JavaScript because everything in your JavaScript will create an instance of each global variable and thus decrease your performance.
I forgot the name of the person, but the man who was heading on optimization at Yahoo! and then went to work for Google gave a lecture about JavaScript optimization, and this was one of his points.
EDIT: Found the link: http://sites.google.com/site/io/even-faster-web-sites
Speed wise 1st way is the best way.
But the best way is to create an XML output from PHP and loading that xml into Javascript via Ajax. The best example of this is article given on google maps documentation - http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
Another way:
In script_that_defines_renderMap.js:
function renderMap(points) {
// take "points" as an argument
}
And then:
<script src="script_that_defines_renderMap.js"/>
<script>
var mapPoints = <?php echo json_encode($this->points); ?>;
renderMap(mapPoints);
</script>
No global variable, no problem.

PHP variable inside a js file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to transfer an array between PHP and Javascript
How do I put the value of a PHP variable inside a Javascript variable?
This is what I have now in a js file:
test=<?php echo $country; ?>;
Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode() for this, as it escapes and encodes your values in a way suitable for using with JavaScript:
test=<?php echo json_encode($country) ?>;
Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.
Also, rename your file to .php instead of .js if you want to be able to insert dynamic PHP code inside it.
Remember that the browser doesn't care what the serverside (PHP) code was. It only cares what the rendered code (Javascript and HTML) looks like. So your PHP
test=<?php echo $country; ?>;
will come out something like this, presuming $country is a string:
test=USA
That is valid Javascript, but it doesn't set test to have the value USA. It sets test to the value of the variable USA, which is almost certainly undefined. You need to use quotation marks to make a Javascript string literal:
test="<?php echo $country; ?>";
This will be rendered as so:
test="USA";
and will do what you expect.
I see now that you've mentioned that the file is a js file. I presumed above that it was a standard PHP-with-HTML file. As it is, everything above is still valid. However, serving a PHP script as Javascript is only slightly tricky.
First, name your file filename.php (or whatever other name you want). This is by far the easiest way to get the webserver to know to parse it with PHP. Then use the following instruction to let the browser know that the file is Javascript content:
header('Content-Type', 'text/javascript');
Put that at the very top of your file, before any content is sent to the browser. You can then include PHP variables as you like.
First of all, to make sure that you understand this, because I see a lot of beginners stumbling over the difference between server side scripting and client side scripting, javascript is a client side scripting language, while PHP is server side. If you understand this, you can basically skip this paragraph. When the user requests a page, such as mysite.com/whatever.php, the request gets sent to the server. Because the user requests the PHP file, the server knows that it should parse the file before sending it to the user. When parsing a file, the server starts n HTML mode, which means that all the text it reads is going directly to the user. From the moment php encounters a or the end of the file. When the end of the file is reached, it sends the output to the user. This output may contain script tags in it's HTML. These peaces of javascript will be executed when they are red together with the HTML by the browser.
However, an external javascript file, doesn't need to have the .js extension, just like css. Therefore, you can also make a php file that outputs js, and do as one of the previous answers suggested, so to put this js code in a .php file:
var somevar = <?php echo $var; ?>;
as you can see, after the equals sign in the javascript, the php variable $var 's value will be printed. This value will therefore be assigned to the js variable called somevar when the output is red by the browser.
put your JS code inside a .php file and try like this:
<html>
<script language="JavaScript">
function echoSession(num)
{
window.document.newForm.mybox.value=num;
<?PHP echo $VAR ?>
}
</script>
</html>
The point is your file should be a PHP file to make server to parse it as php. if it is a .js file it will not work
In order for you to be able to use markup within a Javascript file, you must either:
1) Modify your .htaccess file to include *.js as a valid extension for files to be processed through the PHP Engine. (Google around for this)
2) Change the Javascript file extension from *.js to *.php.
3) Declare variables which are set through PHP within the main PHP/HTML file, rather than the external Javascript file.
There is the json_encode (http://php.net/manual/de/function.json-encode.php) method to print php variables for javascript.
test = <?php echo json_encode($value) ?>
Works even if $value is an array, but in your case if it's a string, too.
This is a problem I face often when dealing with js vs php. As my JS applications become more complex there is more and more a desire to keep all my JS in library files and keep my php as clean as possible. One solution I have started using is to do the following:
js file:
myNamespace.bootstrap = function( payload ){
...
// internally boot up all the modules that need
// the data, passing it where relavent
module.load( payload );
}
php file:
...
<script type="text/javascript">
myNamespace.bootstrap(<?= json_encode($payload_object); ?>);
</script>
</body>
This gives you one data injection point for all your scripts with one line of js in your actual php. Should allow you to easy manage data dependencies in your javascript since you can namespace them in php.

Categories