How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
Related
Hello I built a manual slider using jquery, and I put my images' location inside an array, but now I want to load images from the database, and I want to loop them to a javascript array. How can this accomplished?
<?php
$get = $connect->query("SELECT imagem FROM slider ORDER by id");
while($fetch = $get->fetch_array(MYSQLI_ASSOC)){
}
?>
<script>
var items = ["url(images/banner_1.jpg)","blue","black","green"];
</script>
Here is a simple/low-frills method. It doesn't have any external dependencies as you mentioned.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Use PHP in JavaScript</title>
</head>
<body>
<?php
// assuming your database call returns a valid array like this
$things = array("banner_1.jpg", "banner_2.jpg", "banner_3.jpg", "banner_4.jpg");
// the built-in `json_encode` will make JavaScript like it
$things_json = json_encode($things);
?>
<div class="etc">
<!--this is were the database items will go-->
<ul id="things"></ul>
</div>
<script>
// echo out json-ified PHP directly into the script tag
var things = <?php echo $things_json ?>;
// loop through the json and append list items to our target element
for(var i = 0; i < things.length; i++) {
document.querySelector('body').innerHTML += '<li>' + things[i] + '</li>';
}
</script>
</body>
</html>
The main tricks here are:
use json_encode($your_array_here), which is built in to php
echo the json directly into a script tag in the body.
You can even work with the new things variable from an external script assuming you keep it in the global scope and have your external js run on DOMContentLoaded or similar.
Here are some images of the code working:
Note that json_encode() will only accept one variable at a time. If you need to pass multiple variables down into the script, you can build up an array (map) in php with array functions, or just json_encode() each variable separately and make multiple echo calls inside the script tag.
<?php
// assuming your database call returns a valid array like this
$things = array("banner_1.jpg", "banner_2.jpg", "banner_3.jpg", "banner_4.jpg");
$more_things = array("banner_5.jpg", "banner_6.jpg");
$both_things = array_merge($things, $more_things);
$both_things_json = json_encode($both_things);
?>
<script>
// echo out json-ified PHP directly into the script tag
var bothThings = <?php echo $both_things_json ?>;
</script>
A much simpler method, without adding things in the DOM, and since you asked for a javascript array:
You have to always remember that PHP executes first in server and javascript later in the browser. So you can use your php to create (valid) javascript, like this:
<?php
echo '<script>var jsArray = [];';
while($fetch = $get->fetch_array(MYSQLI_ASSOC)){ // I took your line exactly as you wrote it
echo 'jsArray.push("'. $fetch['field'] .'");'; //you change 'field' with whatever you need
}
echo '</script>';
?>
The output of php script (the code that will be executed by javascript) will be something like this:
<script>
var jsArray = [];
jsArray.push("blue");
jsArray.push("red");
jsArray.push("yellow");
</script>
After that, you will be able to access jsArray.
I have read the following posts, but they are a little over the top for me. I think I'm trying to do something fairly simple, and would like some guidance.
How to pass variables and data from PHP to JavaScript?
passing PHP variables across javascript windows.open to another PHP page
Posting a php variable to a new window
Here is the case:
I have a php script which is very simple, it calls another script and passes 2 variables:
<?php
echo '<script type="text/javascript" language="javascript">
window.open("http://callpage.com/utils/cdr.php?callernum=123456789&calltime=2017-02-22 16:24:12");
</script>';
?>
Note: This is just a "hardcoded" example.
The next script, takes those numbers and builds file/url variable.
Lets say
$file = /var/www/html/file.wav
What I'm trying to do open a new window to the effect of :
http://newpage.com/$file
I have read and found that I think the best use is Javascript, but I can't seem to get my variable into the Javascript.
Here is what I would like to get working:
<?php
$file = /var/www/html/file.wav
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/$file");
</script>';
?>
A few notes:
I don't want to "redirect" the old page, I want it to stay open, and the remote page isn't on the same domain
(one is a.domain.com and the other is b.domain.com).
I don't care about window sizes, etc, its a wav file that I'm expecting the browser to just play with a simple Browser default interface for Wav.
if I understood correctly what you want, you have to concatenate the string with the variable in order to be replaceed
<?php
$file = '/var/www/html/file.wav';
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/'.$file.'");
</script>';
?>
Use string interpolation with double quotes for the echo statement and single quotes everywhere inside the javascript:
echo "<script type='text/javascript' language='javascript'>
window.open('http://newpage.com/$file');
</script>";
The interpolated PHP variable $file should be correctly interpreted as a string and the value it holds should be displayed in the URI of your javascript.
Check out this easy to understand info about variable interpolation http://phppot.com/php/variable-interpolation-in-php/
Here is my "final" code snippet:
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$uid = $row['uniqueid'];
foreach(glob($path. "*". $uid. "*") as $file) {
$link = "http://newpage.com$file";
echo "<script type='text/javascript' language='javascript'>
window.open('$link');
</script>";
}
}
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; ?>');
I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.
I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.