How to Pass PHP Session Variable to external JS file in Symfony - javascript

Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.
Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.
Here is the code section that I need to pass $role to External JS file(in pastebin)
public function executeIndex(sfWebRequest $request) {
if (isset($_SESSION['empId'])) {
$role = $_SESSION['empRole'];
if ($role == "admin") {
$empId = $this->getUser()->getAttribute('empId');
$team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
$nc = new Criteria();
$nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
$resultset = PeDatesPeer::doSelect($nc);
So Can you guys give me a solution regarding this, since I am stuck with this for a long time.
Please see thepastebin code for php and external js file.
https://pastebin.com/kbkLjSFa - PHP File.
https://pastebin.com/M60Rg64U - JS file

Yes you can get the php variable into the js file.
Method I:
Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.
So, if you have some test.js file, rename it to test.js.php and use it in your page like this
<script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>
And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply
var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here
Method II:
Use an AJAX request.
var some_var, another_var;
$.ajax({
url : '/url-which-returns-session-vars', //return the session data in json from this url
asnyc : false,
dataType : 'json',
success : function(res){
some_var = res.some_var;
another_var = res.another_var;
}
});
//rest of the logic goes here.
Both of these methods work. But I prefer the first method, since I don't have to write extra code.
Edit:
Suppose the response of the ajax call looks like this
{
some_var : 'value here',
another_var : 'another value here'
}
So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,
some_var = res.some_var;
another_var = res.another_var;
and since these variables are global variables, you can use them anywhere in your code in this file.

?> <script> var php_variable = '<?php $variable ?>'; </script> <?php
Global variable should be declared before external js file include . in js file access it using this variable name php_variable
After the above code . jquery external file should be included here
<script src="external.js" ></script>
external.js
consol.log(php_variable);

Related

Javascript function not working as externel file [duplicate]

I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.
I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.
Is that possible?
Would I need to "include" the .php file containing the PHP function in the .js file?
How would I do that? For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc. How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js file?
7 years later update: This is terrible advice. Please don't do this.
If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.
<script type="text/javascript">
var phpVars = <?php echo json_encode($vars) ?>;
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>
If you're trying to call functions, then you can do this like this
<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
// assume each element of $arrayWithVars has already been json_encoded
functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Add the above code in .htaccess file and run php inside js files
DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).
If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"
PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.
A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:
PHP File (*.php)
First define an array with the values to be used into javascript files:
<?php
$phpToJsVars = [
'value1' => 'foo1',
'value2' => 'foo2'
];
?>
Now write the php array values into a javascript object literal:
<script type="text/javascript">
var phpVars = {
<?php
foreach ($phpToJsVars as $key => $value) {
echo ' ' . $key . ': ' . '"' . $value . '",' . "\n";
}
?>
};
</script>
Javascript file (*.js)
Now we can access the javscript object literal from any other .js file with the notation:
phpVars["value1"]
phpVars["value2"]
This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.
I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.
Actually the best way to accomplish this is to write the javascript in a .php and use jquery in a separate file to use the Jquery get script file or jquery load use php include function in the doc where the javascript will live. Essentially this is how it will look.
Dynamic Javascript File in a .php file extension - Contains a mixture of php variables pre processed by the server and the javascript that needs these variables in scripts.
Static Js File - Using http://api.jquery.com/jquery.getscript/ or http://api.jquery.com/load/
In the main html page call the static file as a regular js file. Calling the static js file will force load the dynamic data from the server.
some file.php 1:
<?php
$somevar = "Some Dynamic Data";
?>
$('input').val(<?php echo $somevar?>);
or simply echo the script such as
echo "$('input').val(".$somevar.");";
File 2:somejsfile.js:
$("#result").load( "file.php" );
File 3 myhtml.html:
<script src="somejsfile.js"></script>
I believe this answer the question for many people looking to mix php and javascript. It would be nice to have that data process in the background then have the user have delays waiting for data. You could also bypass the second file and simply use php's include on the main html page, you would just have your javascript exposed on the main page. For performance that is up to you and how you want to handle all of that.
Instead of messing with generic php-handlers do a 1-file exception using a rewrite:
Rename the .js-file to .php and rewrite the request to make it responde to a .js request. If the file is served by apache; add in .htaccess:
RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]
Secondly make the .php-file pretend to be a js-file. Inside the php-file start the file with:
<?php header('Content-Type: application/javascript'); ?>
Et voilĂ , you can now use php-tags in your ".js"-file.
You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.
Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!
You can make a double resolution of file:
"filename.php.js" in this way.
PHP generates JS in this file.
I got all parameters from DB.
This worked for me on xampp.
There is not any safe way to include php file into js.
One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.
abc.php
<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>
After use it directly in your js file wherever you want to use.
abc.js
function test(){
alert('Print php variable : '+ abc +', '+number);
}
function printArrVar(){
alert('print php array variable : '+ JSON.stringify(mydata));
}
Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.
this is the standard way you can call php script data into js file without including js into php code or php script into js.

How to use xml pass the data to javascript by DHTMLX

I use DHTMLX. I want to use the ajax component get the data from php, the php will create the xml. How to get this xml data into javascript.
enter code here
dhtmlxAjax.get("php/getUsername.php", function(r){
r = r.xmlDoc.responseXML; // will give you DOM object
//console.log(r.firstChild.tagName);
alert(r.firstChild.tagName("param1"));
});
thank you
Just use the php echo function to echo the php variable into a java script variable.
eg. If you have a php variable called $XMLData you would do the following
var XMLdata = <?php echo $XMLData; ?>
Then on page load your php variable becomes a javascript variable and can be used. from anywhere in javascript provided that the variable is within its scope.

Litle help in php and ajax filies

I got stuck when using ajax as primary request sender to php.
I was trying to send data to php file and then take that data to view in another file, but the problem is I don't know how to do it .
I tried
var ajax = ajaxObj("POST", "function.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
window.location = "view.php";
}
}
ajax.send("a="+a+"&b="+b);
it locate view.php and I want to take contents that sent
function.php and view it's contents in view.php.
That is where my problem occurs.
So, my question is HOW TO TAKE THOSE CONTENTS
I think you don't understand the use of ajax... here you don't need ajax at all. Ajax is used to update/send content without refreshing the page. So if you want to pass data to a new php file, just pass the variables directly to view.php in your case.
For instance:
go to view.php?a=[your value]&b=[your value]
in view.php you can get the values:
$a = $_GET['a'];
$b = $_GET['b'];
and pass it to your function.php
Use Jquery to avoid dealing with browsers specifications and also jquery is pretty popular and simple to use library
Assuming you are familiar with php and JavaScript
first you have to do all this work in you www or htdocs folder depending on the stack you are using whether it is XAMPP,WAMP or LAMP
let's say as an example we want to send post request to function.php file and that file should verify the existance of $_POST['username'] and return the length of username otherwise it returns 0
so the function.php file should be something like this :
if(isset($_POST['username'])){
echo strlen($_POST['username']);
}else{
echo 0;
}
and the view.php file is the file used to send post request and get the response and displays it in a #display div
so here is the content of view.php
// first you should include jquery
// here is a cdn link
// https://code.jquery.com/jquery-2.1.3.min.js
// or you can use a local jquery file it is up to you
<div id="display">
</div>
// here is the simple js code to send and get the data from function.php file
<script>
$(document).ready(function(){
// waiting for the document until it is ready to use
$.post('function.php',{username:'myusername'},function(data){
// data here is the returned data from the function.php file
$('#display').text('username length is : '+data);
});
});
</script>

Yii registerScript : Adding php parameters to javascript

Hi I'm trying to use an external js, the and I'm using Yii clienScript :
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/some.js');
The problem is, in my external js file, I need to pass a url, for my ajax call. and the url is in php, because I'm using the createAbsoluteUrl() below :
$url = Yii::app()->createAbsoluteUrl("/module/controller/action")
How do I pass the $url as a javascript variable to be used by some.js? Thanks!
You could create a JS object at the end of your PHP code.
...
...
$url = Yii::app()->createAbsoluteUrl("/module/controller/action");
...
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/some.js');
<script>
var WRAPPER = (WRAPPER || {});
WRAPPER.url = "<?= $url ?>";
</script>
Then the javascript file some.js should be able to use this as:
var url = WRAPPER.url;
I have done this on CodeIgniter - I'm assuming Yii works similar.

How to call PHP script from within JavaScript

I need help on how to call an external PHP script from within JavaScript.
See below for my example
INDEX.PHP
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>
SCRIPT.PHP
<?php
//script.php
//Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>
First things first: What are you asking is cannot be done in the way you think. When a page is requested, the server runs the php file, and after that it will send you the javascript/html/css page to you. So when you see the page the php script has already done. Javascript is running on your machine, so that's why you can handle with it user interactions.
But, if you send a post request to the script.php, sending the information you want, then you will be able to interact with a php file. To do this, you need jquery. Here is the script how you can do it in jquery:
$.ajax({
type: "POST",
url: "yoursite/script.php",
data: "name="+myName,
success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});
You can download jquery from here: http://jquery.com/download/
After you have downloaded, you have to link it to your index.php the jquery.js file, as a normal javascript file.
In your php file, you can access the name with $_POST["name"], and the information you want to send back, you have to actually print it.
Something like this:
if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}
You can simply write
phpResult = '<?php echo $sometext; ?>';
But,
the js script needs to be in a php file. you cannot use this in .js file obviously.
this will not evaluate any runtime variables on the client side. because the page will already contain vars rendered by the php script from the server.
I use this method all the time specially for rendering php arrays and objects as js objects/arrays.

Categories