I have been reading so many posts and none of them seem to work for me I have no idea what I am doing wrong. I want to call a PHP integer in JavaScript and set it to a JavaScript variable so I am then able to use that variable in my calculations.
average = '<?php echo $average; ?>';
console.log("value" + " " + average);
This is the code I have been using and it prints to the console:
value <?php echo $average; ?>
This is clearly not the resulted I wanted, I wanted it to print the integer.
My $average PHP integer is also located in a different file so I used:
<?php include 'DBObject.php';?>
I want to be able to do a calculation like:
drone1percentage = 1000 / average * 100;
but since the average variable isn't taking the php integer $average from my other file it doesn't work.
You could add this to your .htaccess, so PHP will interpret js files too.
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Or rename that .js to .php and add this header in front of the file:
header('Content-Type: application/javascript');
You "cannot" execute php inside a javascript file.
However there are some tricks to get to your variables from php.
One of them is creating a javascript variable with php and use this variable inside your javascript file.
Example:
// Inside your php file
<script>
var average = <?php echo $average; ?>
</script>
<script src="yourjavascriptfile.js"></script>
// Inside your javascript file
console.log(average);
use jQuery.ajax - http://api.jquery.com/jquery.ajax/
var average;
$(function(){
$.get("path/to/script", function(data, status){
average = data;
});
});
For me the most reliable way to get information from PHP into javaScript is using jQuerys ajax functionality.
So if you have something like
yourPHPFile.php
<?php
if($_POST['action'] == 'getAverage') {
echo returnAverage();
die;
}
function returnAverage() {
//your average calculation here
return $average
}
You could do something like
yourJavaScriptFile.js
var average = null;
$.ajax({
method: 'POST',
url: '/path/to/yourPHPFile.php',
data: {action: 'getAverage'},
success: function(response) {
average = response;
}
});
Just put this inside a function that is triggered whenever you need it.
For this to work you need to have jQuery included. For further information about the jQuery.ajax() functionality see The Documentation.
Please also note that some ajax parameters might differ depending on the version of jQuery you use.
Your js file has to end in .php for example example.js.php in order for the php code to be parsed.
While you cannot put php code into a .js file, you can create a js file from php
You could also setup the web server to parse all .js files as php code, but that would be a bit too much perhaps.
Try this:
average = parseInt('<?php echo $average; ?>');
Related
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.
Suppose I have an external JavaScript file named myJavascript.js which has 3 functions like the following:
function myFunc1(){
//some code
}
function myFunc2(){
//some code
}
function myFunc3(){
//some code
}
Now, I want to add some PHP script in myJavascript.js like the following, and it's from a separate PHP file named myView.ctp:
<?php
$url = Router::url($this->here, true);
$url = explode('/', $url);
$baseURL = $url[0] . '//' . $url[2] . '/' . $url[3] . '/' . $url[5];
$baseURL2 = $url[0] . '//' . $url[2]. '/' . $url[3];
?>
Why I need to add this PHP script inside myJavascript.js is this - I want to use the PHP variables $baseURL and $baseURL2 inside the 3 functions I've created.
How can I achieve this?
Edit:
I'm sorry I actually made a mistake in my question. The php view file is actually named as myView.ctp, as it's a CakePHP view file. The extension is .ctp and not .php. I've updated my question accordingly.
It's possible if you work into an internal HTML file and the extension is php.
Into your myView.php You can declare a global variable, and assign a response server value, into that file.
For example:
myView.php
<script>
var globalVar = <?php echo "your_value" ;?>
</script>
<script src="external_file.js"></script>
external_file.js
console.log(globalVar) // your_value
You cannot use php variables inside a separate javascript file. Instead what you can do is either to include the script inside the php template like
<script type="text/javascript">
....
</script>
or either to parse the url via javascript if this fits for you. You can get the current url with:
window.loacation.href
then you can parse the string as you wish.
I would definitely not do that but instead passing the args to methods or properties.
We usually have one script that takes care of initialization, lazy loading other stuff and so on. This is done in the layout.
<header>
<script src="/js/app.js">
<script>
app.init(<?php echo json_encode($this->request); ?>);
<script>
</header>
Just make sure you pass only what yo need of the request, it might contain security related data, so be careful by passing the whole thing.
In your specific views:
<script>
app.nameSpaceForView.someMethod('<?php echo $someStringVar; ?>');
</script>
You can even avoid this by implementing some logic in the above app.init() function that will check if app.controllers.ControllerName.ViewName is set based on the passed request info and if it's present execute it.
You won't need much, in the best case any, JS in your views by this.
Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>
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.
I have a file like "my_js_stuff.js" which is looking like this :
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
data: ({action : 'get_my_comments'}),
success: function() {
//Do stuff here
}
});
This file is included in my
<header>like this: <script type="text/javascript" src="my_js_stuff.js"></script>
I want to call the function from "my_js_stuff.js" inside my php page, and I'm thinking to call it like this:
<?php
<script type="text/javascript>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
?>
Is this the correct way to call the function from the js file ?
Thank you !
Is this the correct way to call the function from the js file ?
my_js_function() is certainly the correct way to call it.
But, to pass the function so the event can call it later, you'll want to skip the calling parenthesis:
$('.some-class').on('click', my_js_function);
With them, it'll be called immediately and its return value will instead be passed to the event binding.
Also note that the <script> shouldn't be inside a <?php ... ?> block unless it's in a string being echoed.
<?php
# ...
?>
<script>
$('.some-class').on('click', my_js_function);
</script>
<?php
# ...
?>
You could do that, but I'm not sure that's what you actually want to do. Javascript is executed on the client-side, whereas PHP is executed on the server. Your Ajax function makes a request (client-to-server) and fetches content from the server, such as dynamic content generated from a PHP file.
If what you're describing is really what you want to do, you need to echo your script snippet and enclose it in quotes.
<?php
echo '<script type="text/javascript">/*js content*/</script>';
?>
You're confusing the technologies. Your JS is for the client side (browser) and the PHP is for the server side (business logic).
You cannot call a JS function from inside PHP.
However, assuming you want to communicate JS > PHP, you need to include the JS on your page.
<script type="text/javascript?>
$('.some-class').on('click', my_js_function()); // this is the function from the js file.
</script>
and your URL needs to match the PHP endpoint:
url: my_ajax_script.ajaxurl, // This should be the path of your PHP file
Inside the php file you can get all the info as if it were a normal request:
<?php
echo $_GET['action'];
?>
This will return the $_GET['action'] var to your JS success function:
success: function(data) {
alert('Received: ' + data);
}
Hopefully you can use this information to build what you need.