PHP variable inside a js file [duplicate] - php

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.

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.

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 implement php tags in javascript for url's or anything

I was wondering how i could achieve using <?php?> in javascript for url's? There's a certain route you have to go, Anyone know?
the normal way for example:
$fetchContent = $('#div').load('website/members #content');
What i'm trying to do:
$fetchContent = $('#grav').load('<?php?> #poppu');
Yep, thats wrong as hell lol, but i'm sure someone knows
I would also like to know how to tie php with javascript, but thats probably a whole new topic
You said it right :)
Yep, thats wrong as hell lol, but i'm
sure someone knows
Anyway, from your php script, output the url as a javascript code anywhere in the script before the javascript used for ajax call, e.g.
<?php
echo '<script language="javascript"> var g_ajax_url = "'. $the_url . '";</script>';
?>
and in your javascript, use it this way
$fetchContent = $('#grav').load(g_ajax_url + ' #poppu');
What it simply does is define g_ajax_url as a global variable with the proper php value, and you can use that variable in your js as you use other variables.
To tie php with js directly, try looking into xmlrpc topic.
If javascript is in .php file you can use <?php echo $url ?> and if the file is .js you can't use <?php ?>
It is not clear to me what you are trying to achieve. I assume you are using the jQuery load() function, if yes, you should state so.
You can't load php during javascript execution because the php has already been processes and rendered as HTML and sent back to the client. As PHP is processes on the server it is logical that you cannot run it on the client side.
You could of course send an AJAX request to the server that runs a certain php page and you will be able to use the response as you please.
you can't necessarily "tie" them together because they operate in two different spectrums of processing, php being processed on the server, and javascript being processed in the browser.
You can however render javascript within a php file.
if your javascript is included within a <script> tag within your php page your example should work should actually work. The php would render the urls into the script before it is sent to the browser.
if you are wanting to load external javascript files with php inlcuded urls, you will need to set the proper headers and include the php file just as you would a normal .js file.
good article on this topic HERE
You cannot execute <?php ?> inside JavaScript, but inside PHP you can declare a global variable as:
var x = '<?php echo x;?>';
or, if it's an array, store it as JSON:
var x = <?php json_encode(x); ?>
then access the JavaScript variables inside the external JavaScript.

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.

Categories