make a php variable equal a javascript output [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to pass value from javascript to php file
would something like this work?
<script>
var a;
a = 5;
<?php
$b = ?>a;
</script>
I am wondering if I can have javascript parsed by the client-side and have the output information be picked up by PHP as a variable that can be used elsewhere.

You could actually have your JS parsed with PHP if you:
configured your web server to parse .js files, or,
gave your JS file a .php extension and configured the response header with the appropriate content type
e.g.:
<?php header('Content-type: text/javascript');?>
You'd also need to have a PHP include or at least the relevant code to populate the required variables.
Note it's best practice to not use PHP short-tags - your php.ini should be configured to not allow them. i.e., do this:
<?php echo %b %>
instead of this:
<? echo %b %>

that way you cant. The file is first parsed by PHP on the server and then sent to the client-side, where the javascript is parsed.
Without ajax or other kind of requests, data is not sent back to the server.

no, you can't
<script>
var a;
a = 5;
<?php
$b = ?>a;
</script>
on the contrary, you can do this.
<script>
var a;
a = <?echo $b?>; // $b will be the variable of a in javascript (client side)
</script>

Related

php variable inside js code [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 need a php variable inside js code.
Why this doens't work?
index.php
<?php
$h = 966;
?>
index.js
var b = <?php echo $h;?>;
Error:
Uncaught SyntaxError: Unexpected token <
You can't run php inside a JavaScript (.js) file.
Take a look at the question shared by Ed Cottrell in the comment on your post for more information, but basically, PHP is a server language, whereas JavaScript is a client one—when your computer loads index.js, it sees the php script, but has no idea what to do with it.
A straightforward solution (though not the best) would be to output a <script> tag containing your variable inside from your php file— and then access it from your JavaScript file.
When your browser requests the Js file, the web server typically simply sends it the file in the response without processing it like a php file. It doesn't know you have php code in it. It does the same (just sends it to the requesting browser) for images, text files, etc.
You can try doing that in your php view/template/script (I would wrap the output in single quotes). Something like:
<script>var b = '<?php echo $h;?>';</script>
You could also make a JavaScript file with a php extension: index.js.php, and include this instead of index.js. You'll need to set some headers in the top of that file to let the browser know it's getting JavaScript:
header("content-type: application/javascript");
There is some slightly more advanced stuff you can do as well: use an htaccess file to parse certain requests (like for that Js file) using php, or using an asynchronous request (Ajax) to pull the value of 'b' from the server, but it looks like your doing something a bit more simple.

How to use javascript to access php variable? [duplicate]

This question already has answers here:
How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?> [duplicate]
(6 answers)
Access PHP variable in JavaScript [duplicate]
(3 answers)
Closed 10 years ago.
How to use javascript to access php variable?
Does only one way to write code (like var a={?echo $variable})in javascript?
Recommend some books on php and javascipt(include projects)?I don't know how to use knowledge in projects?
Yes, you were correct.
Because PHP is executed before JavaScript, you can't change it later on, but you could do something like this:
<? $aVar = "whatever"; ?>
...
<script>
var aVar = "<? echo $aVar; ?>"; // note the quotes! (SO's highlighter renders this incorrectly, starting a PHP block inside quotes is valid and will be recognized.)
</script>
That will send this to the client:
<script>
var aVar = "whatever"; // note the quotes!
</script>
var a=<?php echo $variable; ?>
PHP runs in server and js in client side, so Iguess there is not other you can get it. OR you need to use AJAX
I don't see how can you do that in any other method. PHP is server side, while JS is executed on client's PC (not on the web server). Theoretically and practically it's not possible.

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.

Include PHP inside JavaScript (.js) files

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 do I access a PHP variable from JavaScript?

How do I call PHP variables or queries in JavaScript?
<script>
var foo = <?php echo $foo; ?>;
// or, if foo is a string;
var foo = '<?php echo addslashes($foo); ?>';
// for anything more complex, you'll need to use json_encode, if available in your version of PHP
var foo = <?php echo json_encode($foo); ?>;
</script>
Please note, you can only do this one way. Don't expect any changes you make in javascript to come through to PHP.
PHP and JavaScript cannot mix directly. You use PHP server-side to generate and send JavaScript to the client. the JavaScript executes client-side and can communicate with PHP code on the server only via AJAX calls. This can be simplified drastically through the use of an AJAX library like jQuery.
You have to keep in mind that your PHP code is evaluated on the server, while JavaScript (normally) runs in the browser. The evaluations happen in different times, at different places. Therefore you cannot call a JavaScript function (or variable) from PHP, simply because you cannot call a function that exists on another computer.
You may want to check if Ajax is an appropriate solution for your problem.
Generally, you can't. PHP is server-side and Javascript is client-side (processed by the browser).
The exception is to use AJAX, which allows you to access PHP pages, which should then execute the action needed.
You can use JSON for this purpose which serves well for sending a big array to Javascript from PHP. We need to echo JavaScript code in PHP script or we can use Ajax for this. But usually we may need to send a big array. So we can do like this
<script>
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
?>
var foo = echo json_encode($arr);
</script>
The json_encode function will handle all escaping and other issues. Bug also make sure json_encode is available in your PHP version.

Categories