How to access a session variable in a .js file in CakePHP - javascript

In my CakePHP application I am creating a session variable in some controller, which I need to access in a ".js" file. Is there any possible way to do this?

I would suggest passing them as parameters like this -
<a onclick="some_function('<?php echo $_SESSION['var'] ?>')">Click</a>
and have the javascript function some_function() process it instead of assigning them inline. This way you can have the javascript file free from server side code. This is the cleanest way.
I too feel that because session variables are server side, they should not be handled directly in client side language through inline code.

You need to dynamically generate your JS file so that it contains the value you want. You can set up your server to parse .js files through PHP, or you can just name the JS file .php:
var myVar = '<?php echo addslashes($_SESSION['myVar']); ?>';

Related

Spring message in javascript file

I'm trying spring:message tag to my javascript file, but nothing is displayed. In jsp file and tag spring:message works fine, but if I put js code to js file it's not working.
In js file I use:
password: '<spring:message code="account.enterPassword" />'
Sorry for my bad English.
Spring tags renders on the server side and javascript works in client after server side process is complete. But you can put an <script></script> tag inside your jsp, define your variable on it, and then access your global javascript variable in your external js file:
jsp:
<script>
var password: '<spring:message code="account.enterPassword" />'
//any other variables you want to use
</script>
Now, you can access the password variable inside any other js file.
Note, this script tag must be at top of your js files that you want to variables on it. Also, be careful when picking a name for global variables, because, local variables can override global variables in case of common name.
It is not possible for javascript to have access to a spring tag. spring:message is processed server-side before the page is sent to the client, javascript/jQuery is processed later on the client side.
As a workaround, put the message value in a hidden input on your jsp page. Then get its value in your javascript. In your case:
<c:set var="val"><spring:message code="account.enterPassword"/></c:set>
<input id="enterPasswordId" type="hidden" value="${val}"/>
In your javascript (using jquery) you can then use it as follows:
$('#enterPasswordId').val() //jquery
document.getElementById("enterPasswordId"); //javascript

Transferring data from PHP to Javascript for processing [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have a variable set in the PHP with some relevant information that I need to process with the Javascript, but I can't figure out how to port that information over to the Javascript.
I first create a test variable in one javascript file, x
Test='<--!TestString-->'
In the PHP I use str_replace to alter the value of the variable with the relevant data
str_replace('<--!TestString-->',seralize($data), x)
Now I try to see if the data has been added in a different file using alert(Test)
and it shows me <--!TestString-->
Is there a better way to do this and have the data show with the alert function so I can start processing it?
I don't understand your approach at all.
Of course the ideal way to accomplish is to use AJAX to grab data from the server and get into the client side so you can work with it in Javascript. (You can Google "Ajax php and javascript")
The easiest way to accomplish this is to just print the variable in PHP but in a context that it will be available to JS in the client.
<html>
<body>
<script>
var x = <?php echo json_encode($phpvar); ?>;
console.log(x);
</script>
</body>
</html>
I won't argue with anyone that disapproves of that approach but its easy and it works.
Use <script> tag?
<script> my_value = 'some'; </script>
Use AJAX?
// with jQuery:
$.get('/data.php',function(data){/*...*/})
PHP is executed on your server, Javascript in the client (ie. Browser of the user visiting your website). So PHP can not change variables of your JS code once the page has been sent to the browser. But what you can do is set the variable in PHP and insert it in your JS code like this:
<?php
$test="some important info here";
?>
<script>
alert("<?php echo $test ?>");
</script>
If you need to change the variable by the server, you would need to use AJAX to load the new value.
As mentioned before we might not be understanding your approach to your problem.
PHP is executed on the server side while Javascript in the client. PHP cannot change variables of your Javascript code once the page has been sent to the browser. What must be done is to invoke PHP by using preferably AJAX with jQuery.
Look into AJAX PHP with JSON. Perhaps you are looking into the json_encode(value) function?

How to use variables from a php file in a js file?

I have the following file structure:
Now I want to use the variables from the dropdown menu's (that are in the get_attributes.php, get_fields.php and in the get_tables.php) in my main.js and in getData.php . Now the question is how can use a variable from another .php file in a .js file?
You can't directly use PHP variables from JS scripts.
Dynamic access
If you want get variables dynamically you can use AJAX (see jQuery AJAX doc ).
Static access
If you want to access PHP variables when your JS app start you can put PHP variables in the DOM by using this syntax :
<input type="hidden" id="php_name" value="<?=$name?>" />
And use jQuery to get it :
$('#php_name').val();
I hope it will help.

PHP include Javascript-generated filename?

while(x<=num_of_cpkgs){
var cpkg_navtray = '\'navtrays/' + cpkg_array[x] + '.html\'';
<?php include ?> cpkg_navtray <?php ; ?>;
x++;
}
cpkg_array contains potentially multiple file names. I'm wondering if there's a way to include a Javascript-generated filename in a PHP include statement like this?
This doesn't work like this.
TL;DR:
You need AJAX calls for this.
Longer:
When you load a page in your Browser, the server send you the file. If the file is a php file, then it calls the php to process the file. After the file is processed the server send it to you as a static file.
With JS you can do some interaction to the website. Until now you probably got used to sending each file as a GET or POST data with a form. With JS you have to make an XMLHttpRequest to create a dynamic request and your page is won't be refreshed again however you will get the response as a variable in JS.
Read all about this here.

"Unexpected token <" when using <?php in a Javascript file

Being new to this, I'm trying to pass a variable from PHP to Javascript.
In my php page, I use a test variable:
$testval = "x";
In my .js file:
var exarr = <?php echo json_encode($testval); ?>;
I've tried several things, but it seems I always get Unexpected token < when I include "
What am I doing wrong ?
Thanks !
In order to use PHP code in any file, the web server has to run that file through the PHP processor. This is configured to happen by default with .php files, but not with .js files.
You could configure your server to process .js files as PHP, but that's generally unwise. At the very least, it creates a lot of unnecessary overhead for those files since most of them won't (or shouldn't) have PHP code.
Without knowing more about the structure of what you're trying to accomplish, it's difficult to advise a "best" approach. Options include (but may not be limited to):
Defining that one var on a PHP page which references the JS file, thereby making it available to the JavaScript code.
Putting the value in a page element somewhere that it can be accessed by JavaScript code, either as a form value or perhaps a data value.
Making an AJAX request to the server to get that value (and other values) after the page has been loaded.
If you have that in a js file (like somefile.js) then PHP isn't going to parse that file by default. In the PHP file that links to that JS you can output a script tag and the var you want like:
echo "<script>var exarr = " . json_encode($testval) . "; </script>";
And make sure your script is linked in after that code;
.js files are not compiled by PHP. The easiest workaround is to put the Javascript in a <script> block within a .php, but you're making one of the most basic of serverside/clientside mistakes and should rethink your entire approach.

Categories

Resources