I have a captcha generator php script:
<?php
session_start();
header ("Content-type: image/png");
/*irrelevant parts here*/
$word = "";
for ($i = 0; $i < 4; $i++) {
$letter = $letters[rand(0, $len - 1)];
imagettftext($image, 15, 0, $i*50+25, 50, $text_color, $font, $letter);
$word .= $letter;
}
$_SESSION['captcha_string'] = $word;
imagepng($image);
?>
I call it this way in my HTML/PHP page:
<?php session_start(); ?>
<!DOCTYPE html>
.. some irrelevant code here ..
<img id="captchaimg" src="captcha_generator.php">
And this is my javascript code which is on the same HTML/PHP page (I call this function with a button click):
<script type="text/javascript">
function validCaptcha() {
var a = <?php echo json_encode($_SESSION['captcha_string']); ?>;
alert(a);
}
</script>
My problem is that the javascript "is late", it gets the previous value of the session variable, not the actual. I think the reason is that when the page is loading the php runs AFTER the javascript did get the session variable. So, the javascript sees the previous session variable, while there is already a new one.
How can I get the ACTUAL session variable in the javascript function?
UPDATE to the question: when does the javascript function get the session variable? When the page is loading or when the user clicks the button?
1.Here problem is the while loading page only variable a= sessionvalue assigned with session value.
2.Here you are creating captcha code after loading page and reassigning session value.
3.In php session value get updated.But in JS doesn't.
one alternative solution is send ajax call when you click on button and return session($_SESSION['captcha_string']) value from PHP. This could resolve your problem.
OK, I found the solution. The key >> I had to make a new php file (called captchavalue.php in the example) which only has one task: echo the variable:
<?php
session_start();
echo $_SESSION['captcha_string'];
?>
And here is the Ajax/Javascript (thanks for suggestion):
<script>
function validCaptcha() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("div_id").innerHTML = this.responseText;
}
};
xhttp.open("GET", "includes/captchavalue.php", true);
xhttp.send();
}
</script>
Related
I have a function.php code simple one:
$var = "7000";
and I have another file script.js:
var Price = <?php echo $var ?>;
now it works when this code in the same file.
but when I separate the files its doesn't.
any suggestions?
As pointed out by GrumpyCrouton in his comment to you, variables out of one file can be read in another by including them
<?php
include('file1.php'); // include the file where the variable is defined
<script>
var Price = <?= json_encode($var) ?>; // in javascript code export the variable to js usign json
</script>
It is always safe to use json_encode and dump the variable directly into js no need to encapsulate it any more then that, I would add a semicolon at the end but that is more of a personal preference in this day and age.
Create a script called price.php with the following content:
<?php
header("Content-type: text/javascript"); // As suggested by Mark Eriksson
$var = "7000";
?>
const PRICE = <?php echo $var; ?>;
Now you can reference this JavaScript block on any HTML page:
<script src="price.php"></script>
You will have a global JavaScript variable (constant) called PRICE.
Do you need variable prices? No problem, you can pass a value as a parameter, for example:
<script src="price.php?price=8500"></script>
And in your price.php, you change it to:
<?php
$var = $_GET["price"];
?>
const PRICE = <?php echo $var; ?>;
Your HTML page still gets a constant named PRICE.
Well, if you want to access some PHP variables, then you need to use AJAX.
Its quite simple.
Do this inside function.php file
<?php
$var = "7000";
// Put your price into array to form it into JSON format further
$data = ["price" => $var];
return json_encode($data);
And following in your JS file.
let xhr = new XmlHttpRequest();
xhr.open('get', 'function.php', true);
xhr.onload = function() {
if (this.status == 200) {
var data = JSON.parse(this.response);
// Your final result
var Price = data.price;
}
}
xhr.send();
I'm having problems with passing php variables to javascript.
It does pass through the variable that is declared at the top, but I don't know how to call the function to get the new version of variable after the IF statement is done.
$info = "A message";
if (true){
$info = 'Message to be passed';
}
The script that is used to pass the php variable to javascript file:
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
</script>
I was wondering what could I do to fix this problem?
The simple way (this requires both files to be PHP files):
<?php
require_once "your_php_file_here.php"; // Change to your PHP file here
?>
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
alert(info);
</script>
This will only allow you to get the value on page load. You need to reload the page if you want it to get a new value.
The (in my opinion) better way (the file can be HTML) using Ajax:
<script type='text/javascript'>
var info;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your_php_file_here.php'); // Change to your PHP file here
xhr.onload = function() {
if (xhr.status === 200) {
info = xhr.responseText;
alert(info);
} else {
alert('Request failed: ' + xhr.status);
}
};
xhr.send();
</script>
This can be put in a function and called as many times as you want. It can get the new value without the need to reload the page.
For this to work, you need to change your PHP code to:
$info = "A message";
if (true){
$info = 'Message to be passed';
}
echo $info;
I did not add support for IE6 and below because I think it's about time we stop supporting browsers that lost support by their developers many years ago.
ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
first I have a php script on test.php on the apache server
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
I'm quite new so any advise would be appreciated, thanks.
The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object.
So first your JS code should be:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1 variable:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
so if we do this:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
You should define the PHP variable. And use that variable in your javascript:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>
I create a session in my php script.
I want to destroy my php session in javascript.
when I click on Destroy Session then javascript function destroy() call and destroy SESSION['user'].
<?php
ob_start();
session_start();
SESSION['user'] = "test 123";
echo "<a onClick = 'destroy()'>Destroy Session</a>";
?>
<script>
Function destroy(){
session_destroy(); // Like `PHP` I want destroy Session in `javascript`
}
</script>
I think you should use AJAX to destroy function from Javascript. Like :
.js code :
function destroy_session(){
var xmlhttp = getXmlHttp();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','./destroy_session.php', true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
destroy_session.php code:
<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
echo 'Session was destroyed';
?>
you cant directly destroy the session of php within javascript, since javascript is running on the client and php is running on the server.
but you can erase the session cookie from php within php - when its used!
but this detaches only the client from the session, no destroying the session.
What you can do is use AJAX to load a PHP page that executes a session_destroy(). jQuery has very easy ajax functions, documented here.
<script language="javascript">
function emergency()
{
if(document.getElementById('emer').checked == true)
{
<?php $_SESSION['total2']= $_SESSION['total1'] + 50; ?>
document.getElementById('emr').innerHTML = "<b>Payable Amount: </b>" + <?php echo $_SESSION['total2']; ?>;
}
if(document.getElementById('emer').checked == false)
{
<?php $_SESSION['total2']= $_SESSION['total2'] - 50; ?>
document.getElementById('emr').innerHTML = "<b>Payable Amount: </b>" + <?php echo $_SESSION['total2']; ?>;
}
}
</script>
here I am adding $_SESSION['total1']+50 and put the value in new session SESSION['total2']. The problem is that , when I echo this new $_SESSION['total2'] out side script,ie, in the page like
<?php echo $_SESSION['total2'];?>
it returns the value of $_SESSION['total1']).
Are you calling a javascript function to change value of php session variable?..
this could not be possible because, php is a server side language and javascript is client side so php code gets executed when the page is loaded..
so if you want to do this on javascript function call,, than you need to use ajax...
to get the new value of $_SESSION['total2'] you have to run the code on server side again. that means before getting the new value for total2 session variable you have to reload the appropriate php file.