This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I know its REALLY simple, but I'm a newbie. I want to pass a variable from a PHP query via JS (for open-flash-chart) to the data file which is PHP.
This is my JS inside my PHP file. I'm pretty certian my issue is with the JS part since I've never used it before.
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript">
var player = "<? echo $player1 ?>";
swfobject.embedSWF(
"open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data2.php"} );
</script>
I am trying to pass the $player variable to the graph data file which is this ( data2.php)
<?php
include("include/session.php");
include 'open-flash-chart/php-ofc-library/open-flash-chart.php';
if (isset($_GET['player'])) {
$player = $_GET['player']; }
$sql = "SELECT pos FROM nflscore where username = '$player'";
Assuming you want to use the var player change this in your swfobject.embedSWF call
{"data-file":"data2.php?player=" + player }
data2.php?variable="whatever variable"
on the php side do
$variable=$_GET["variable"];
now variable is the variable that you passed and you can do what you want with it
Well it pretty much depends on your needs!
Will javascript alter that variable? if not, the best way to transfer data between php pages are sessions! there are other options such as cookies, get vars, post vars etc. but users may change them putting your script in an uncomfortable position of dealing with wrong information if users do!
Using sessions your first page would simply look like this:
<?php session_start(); $_SESSION['player'] = $player; ?>
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data.php"} );
</script>
<!-- [...] -->
session_start has to be put at the very beginning of your php file, no headers should be sent before that function!
Well, your data file would then just become something like this:
<?php session_start();
/* ...your includes and the rest... */
$sql = "SELECT pos FROM nflscore where username = '{$_SESSION['player']}'";
Using cookies instead is quite the same, you just don't have to start the session at the beginning of your script (but if its a game you should rely on them already)! whats best though, you can access the cookie afterwards in your javascript as well!
so that's what your first page should look like :
<?php setcookie('player', $player) // somewhere in the script ?>
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf", {"data-file":"data.php"} );
</script>
<!-- [...] -->
an your data page also becomes :
$sql = "SELECT pos FROM nflscore where username = '{$_COOKIE['player']}'";
The third easy option is to just drop the information where it should be right from the beginning ;) so no sessions, no cookies but just plain get variables!
first file :
<!-- [...] -->
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "900", "350", "9.0.0", "expressInstall.swf",
{"data-file":"data.php?player=<?php echo $player ?>"} );
</script>
<!-- [...] -->
second file :
$sql = "SELECT pos FROM nflscore where username = '{$_GET['player']}'";
Things become different though if your javascript needs to change the variable's content
Related
Here I want to use session variable's value in javascript function. I tried
var varname = '<?php echo $_SESSION["variable_name"]; ?>';
But it doesn't pass the value it shows the string
so how can i use session variable of php inside the javascript.
Actually I want to check captcha code in java script side.
Here i already make contactus.php file where I generat captcha value from rand function. Then i store this value in session variable. Here I already made validation.js file to validate contact us form fields so in same file i want to validate captha so for that I has been trying below code but its not working .
var cap = document.frm.captcha.value;
var ca = '<?= addslashes($_SESSION["code"]); ?>';
alert (cap); //ITs shows my entered value perfectly
alert (ca); //but it doesn't show generated captcha value. it simply print '<?= addslashes($_SESSION["code"]); ?>'//
if(cap!=ca)
{
alert("Insert correct captcha code");
document.frm.captcha.focus();
return false;
}
I checked session variable value it works fine on php page but dosen;t work on javascript page.
<script type="text/javascript">
<?php echo "var variable = '". $_SESSION['variable']."';" ?>;
</script>
The file which contains this code must be named .php and has to be a session_start(); at the beginning of the PHP-File.
Then this code should work.
There is several posibilities, why your code isn`t working.
There is an error in variable (Eg unescaped quote)
Code is outside of Javascript code.
Session is not started in the moment of getting variable
For fixing this 3 errors you need to use following code -
<?php session_start(); ?>
<script type="text/javascript">
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
</script>
If in your session variable is not a string or number you need to pack it to the JSON object. In this case you can just make following:
<?php session_start(); ?>
<script type="text/javascript">
var varname = <?= json_encode($_SESSION['variable_name']); ?>;
</script>
Last variant of code will make all types of variable are frendly to JS. Also string.
For example with json_encode from asd'd"sa string you will get "asd'd\"sa" string.
UPD:
If you use this file like JS file like follows:
<script type="text/javascript" src=".../path/to/file.php"></script>
for correct work you need to use following code.
<?php
session_start();
header('Content-Type: text/javascript');
?>
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
Try like this:
<script type="text/javascript">
var varname = <?php echo $_SESSION["variable_name"]; ?>;
</script>
This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
Yes I know this question gets asked a lot, but I'm fairly new to JS and I need to use a php variable in some JS. I'm more then aware that PHP is executed server side and JS is client side however other people claim that this works.
I've got a PHP variable called "test1" that I want to log to the JS console (for instance):
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>';
?>
What this does is print " " to the JS console. Not exactly what I was hoping for.
Now this may not even be doable and I may have to pass the variable off the page and back in again with AJAX, but I'd rather have a quick and easy solution if there is one available!
Any help is appreciated.
You could do this.
<script>
var JSvar = "<?= $phpVar ?>";
</script>
The PHP will be parsed and the value of $phpVar will become the value of JSvar whatever.
Make sure you encode phpVar properly. For example, if phpVar contains a double quote, you'll end up with a broken JS
Use this no need to give "" => change to '.$test1.'..
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "'.$test1.'"
console.log(carnr);
</script>';
?>
try
<?php $test1 = '1'; ?>
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>
Generally, it is better to not print static stuff with php, but to have static (that is unchanging) stuff directly in HTML and only use PHP on the parts that really need it.
You made a mistake do it so:
<?php
$test1 = '1';
echo '<script type="text/javascript"> var carnr; carnr = "'.$test1.'" console.log(carnr)</script>';
?>
Since you're writing your JS with your PHP, you can simply do:
$test1 = "blah";
echo "<script type=\"text/javascript\">console.log($test1);</script>";
You are already in open php tag. When printing the line just append the variable to the output by using a dot.
Example:
print 'variable1 '.$variable1.' is now printed';
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)
So I'm wondering if it's possible to access the data in a php variable, in a jquery/javascript script. Say I have a wordpress query/loop, that brings up a particular post from the database.
Then if I store that post in a php variable, is there any way I could reference that variable/post from within a javascript/script?
Yes. You can.
Scenario: 1 If HTML and PHP are in seperate files
HTML
<html>
<head>
<script type='text/javascript' src='code.php' runat='server'></script>
<script>
// you can get phpVar here
alert(phpVar);
</script>
</head>
<body>
</body>
</html>
code.php
<?php
$value =" Value from PHP";
echo "var phpVar = '". $value ."'";
?>
Scenario: 2 If HTML and PHP are in same file
<?php $value =" Value from PHP"; ?>
<html>
<head>
<script>
<?php echo "var phpVar ='" . $value ."'"; ?>
alert(phpVar);
</script>
</head>
<body>
</body>
</html>
You can do the below on a PHP page.
<script>
alert("<?php echo $hello_world;?>");
</script>
This won't work in a .js file, however, as it obviously isn't set to interpret PHP syntax.
So when your browser initiates a request, it hits the server. The server processes the request, running through all the necessary methods and setting variables, and then it sends the result back to the browser. At that point, anything not in session dies on the PHP side (i.e. it's not persistent) so there's no way for javascript to access this php variable.
If what you'd like to do is to pass a php variable or object to a javascript function, I'd recommend using json_encode:
http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
You could output information about the post inline in a script tag like this (assumes you're in the "loop" and only outputting one post):
<script>
var post_id = <?php the_ID(); ?>;
var post_title = "<?php the_title(); ?>";
var post_excerpt = "<?php the_excerpt(); ?>";
</script>
However, depending on what you're trying to accomplish you may want to approach this differently. Perhaps using a script to output post data in JSON format so that it can be natively understood by javascript then writing AJAX functions to retrieve and render those posts. Here are some resources that may be helpful:
Wordpress JSON API
jQuery AJAX
Is there any scenario where a client/user/hacker can set $_SESSION variables themselves (excluding malicious software running on a server computer. I mostly mean via the browser)?
The reason I ask is because of this question that I asked a few days ago. Since then I have become pretty confused on the subject, but I've got a better idea of session fixation and hijacking.
To put it as simply as possible, if I validate every page with something like isset($_SESSION['validated']), is it secure?
Yes if you were assigning $_SESSION variables directly to unfiltered user input.
Which brings me to my point: NEVER TRUST INPUT FROM THE USER. EVER
If indeed you are filtering the input, then I don't see how it could be done.
Yes, it's possible. Read about Session poisoning and another quite common security issue Session fixation on Wikipedia or Google it - the web is full of articles about that.
I don't think $_SESSION variables can be changed unless the user has server access otherwise no they can't change it but filtering the variables or sanitizing it is recommended if it is something the user enters.
I do not quite understand the question, but this question explains my way of what I think that you want to do.
Make sure that you include jQuery.
Code:
<html>
<head>
<title>Tab name</title>
<meta charset = "UTF-8" />
<script type = "text/javascript" src = "http://code.jquery.com/jquery-1.1.13.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</head>
<body>
</body>
</html>
Then make a file called addsession.php.
Code for addsession.php:
<?php session_start(); ?>
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
} else {
print '<p style = "color: red; font-weight: bold;">Name not defined!</p>' . "\n";
$name = "unknownsessionvariable";
}
if(isset($_POST["value"])){
$value = $_POST["value"];
} else {
$value = "";
}
$_SESSION[name] = value;
?>
Code for script.js:
function session(name, value){
$.post(addsession.php, {"name" : name, "value" : value});
window.location.reload(); // This line maybe should be here depending on what you are doing.
}
$(document).ready(function(){
session("sessvar", "supervalue");
});
Example code snippet:
function session(name, value){
$.post("http://www.eastonwerling.com/addsession.php", {"name" : name, "value" : value});
//window.location.reload();
$(document).ready(function(){
session("sessvar", "supervalue");
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<p>This example depends on www.eastonwerling.com (my website).</p>