PHP variable is empty when called in jQuery script - javascript

I'm having a little trouble calling a PHP variable into a jQuery script. Basically, I run a few functions to determine if a user is logged in and, if so, store that as $loggedin=1. If a person that is on a page is NOT logged in, when a button is clicked I want them to be prompted to sign in (I'll obviously still ensure the user is ACTUALLY logged in on the server side before any processing of data). I searched around, and found the easiest way to get that information over to jQuery is to create the script as a PHP file so I can echo it into the script. Here is the high level code I'm using:
Call up the script:
<?php
$loggedIn = 1;
<script src="../buttonScript.php"></script>
?>
Script:
<?php header("Content-type: application/javascript"); ?>
var buttonScript = function(){
var loggedIn = <?php if($loggedIn===1){echo "1";}else{echo "0";} ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
When I click the button in a situation where $loggedIn is equal to 1, the alert gives me 0. In fact, if I simply echo $loggedIn in the script itself, the value is completely empty and the script errors out and won't pop up an alert at all. I'm confident that the PHP variable $loggedIn actually has a variable, since if I echo the variable right before the script is called, I successfully see the number 1. What am I missing here?
Note: added a couple lines in the script calling just for clarity.

Try this
<?php
$loggedIn = 1;
require("/path/buttonScript.php");
?>
buttonScript.php
<script type="text/javascript">
var buttonScript = function(){
var loggedIn = <?php echo $loggedIn; ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
</script>

Related

Why my confirm "alert" don't work on my code?

This is a page of a web app, and the job is simple:
I can see the "alert" that asks me whether I want to confirm or not. Based on the answer, I move to other pages.
If i sent my "if" cicle, the "alert" it's showed. This is the code
<?php
session_start();
include('../Model/gestoreAccessi.php');
include('connect.php');
?>
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = <?php header('Location: http://www.teamjg.altervista.org/Matteo/navbar.php');?>
else
<?php
session_start();
session_unset();
session_destroy();
header('Location: http://www.teamjg.altervista.org/Matteo/index.html');
?>
</script>
So, before I answer your question; just a note. PHP and Js will run on different machines (even though you're testing it on your localhost, still consider them as different machines)
All PHP code is run, and executed on the backend before anything is sent to your browser, after which js code is executed. PHP does not understand JS syntax, it will only look at <? and ?> tags and execute everything inside them.
<?php
session_start();
include('../Model/gestoreAccessi.php');
include('connect.php');
?>
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = <?php header('Location: http://www.teamjg.altervista.org/Matteo/navbar.php');?>
else
<?php
session_start();
session_unset();
session_destroy();
header('Location: http://www.teamjg.altervista.org/Matteo/index.html');
?>
</script>
When this code is being sent by XAMPP (or whatever engine you use), the PHP is first executed which will make the code look like this:
// Session will be started
// contents of ../Model/gestoreAccessi.php will be copied and run
// contents of connnect.php will be copied and run
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = //The header is already set
else
// Location is already set
</script>
So this is undefined behaviour as you are sending two header tags with different locations, my best guess is it will redirect to http://www.teamjg.altervista.org/Matteo/index.html.
One thing you could do as a hotfix is set window.location.href if you want to redirect your user to some other website. Read this.

how to hold javascript variable in php variable

I want to use javascript variable as php variable. I am echo php variable then its print. but when i am use for fetching data from database its show an error
Notice: Undefined index: document.write(i)
here my code
javascript
var i=0;
function inc()
{
i+=1;
}
<?php $foo="<script>document.write(i)</script>"; ?>
php
code work for
echo $foo
code not work for
$i=$foo;
$query="select * from TABLE where id = $i";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_row($result))
{
echo $row[0];
}
Then It show This Error Notice: Undefined index: document.write(i)
PHP is server-side code that is run to generate a page. Javascript is client-side code that is run after the page is sent to the visitor's browser. Javascript can't affect the server-side code because the server code is done running by the time the Javascript runs. If you want to have a user's selection change the behavior of the PHP code the next time the form is loaded, pass a variable through a $_POST variable when the form is submitted.
If you want your PHP and Javascript code to be using the same value, have the PHP code write a Javascript variable initialization into the page's <head> section before any Javascript would run that would need to use it.
<script>
var i=0;
function inc()
{
i+=1;
return i;
}
</script>
<?php
$foo = '<script type="text/javascript">document.write(inc());</script>'; //Script function call which return the var i value to php variable
echo $foo;
?>

How to read a session variable from a php file in JavaScript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There have been far too many questions on this subject but I still fail to understand.
Case:
Hyperlinked image
OnClick of image: Check if session exists
If session exist, open link
If session does not exist, show login form
onclick is calling a JavaScript function:
var my_global_link = '';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
// .. then show login modal that uses 'js/whitepaper-login.js'
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
Global variable is being saved in another php file as :
$_SESSION['logged_in'] = 1;
I am unable to capture the session value in the var check. Can you advise?
Using jQuery here is a simple example of how to get a PHP $_SESSION into your JavaScript:
session.php
<?php
session_start();
$_SESSION['foo'] = 'foo';
echo $_SESSION['foo']; // this will be echoed when the AJAX request comes in
?>
get_session.html (assumes jQuery has been included)
<script>
$(function() {
$('a').click(function(event){ // use instead of onclick()
event.preventDefault(); // prevents the default click action
// we don't need complex AJAX because we're just getting some data
$.get('session.php', function(sessionData) {
console.log( sessionData ); // session data will be 'foo'
});
});
});
</script>
click
If this is successful you'll see the data and can use it in other JavaScript functions by passing the data appropriately. I often find it handy to json_encode() session data, returning JSON to be used by JavaScript, but there is no need to in a simple example such as this one.
Make the request to someone file.php
$( document ).ready(function(){//run when DOM is loaded
$.post("file.php", //make request method POST to file.php
function(data){ //callback of request is data
var arr = jQuery.parseJSON(data); //make json decoding
if(arr.logged == 1) //arr.logged is value needs
#do
})
})
file.php
<?php
session_start(); //start session for my dear friend Jay Blanchard
$_SESSION['logged_id'] = 1; //init value for example
$array = array('logged' => $_SESSION['logged_id']);//creat array for encoding
echo json_encode($array); //make json encoding for call back
?>
your javascript is not a very good solution, as it can be hacked easily. One can simply change the value of check to whatever one likes, and even without a login one would be able to access the link of the picture.
A better implementation would probably be something like:
<img src="img.png" alt="" />
checklogin.php would then verify the $_SESSION variable. If validated, you can use header("Location: something.html"); to redirect to where you want to bring the user. If not logged in, you can instead redirect to the login page: header("Location: login.php");
#Sarah
You have to first call the php file via ajax and set the javascript variable as the result. Since the javascript is a client side scripting language hence it can't read server side PHP script.
Hence on click call javascript function
function someFunc(){
//Fire Ajax request
//Set check variable
//and perform the function you want to ...
}
<?php include "sess.php"; ?>
<script type="text/javascript">
var my_global_link = 'testr.com';
var check = '<?php echo $_SESSION["logged_in"]; ?>';
function show_login( link ) {
if(check == 1)
{
window.location = link;
}
else
{
my_global_link = link;
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
</script>
<a href="#" onclick="show_login('test')" >test</a>
file1.php
<?php
session_start();
$_SESSION["logged_in"] = 1;
?>
sess.php
I have done this using two files. You may have not included session file I guess. Its working fine for me.

Javascript game info to PHP

So after the player loses I want their score to be updated into the database using PHP.
I have a separate javascript class that actually runs the entire game but it uses setInterval to check the index.php function to check if the player lost; if they do they I want it to update the database. The update works but its not taking the score and is just replacing whatever highscore they had with 0.. obviously not what I want. I know people are going to recommend AJAX but my professor only wants PHP and Javascript so I'm getting really confused here... heres the function inside the index.php
<script type="text/javascript">
function checkFinished(){
if(end()){
<?php
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
$userName = $id["name"];
$update = "UPDATE bloodred SET score='?>score<?php' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
?>
gameover = false;
}
}
</script>
as you can see im trying to grab the javascript variable score by doing this in the $update variable
score='?>score<?php'
does anyone know any quick short cuts to do this? thanks !
Javascript is client side, and PHP is server side. When you remove the PHP from your javascript, you end up with this:
<script type="text/javascript">
function checkFinished(){
if(end()){
score
gameover = false;
}
}
</script>
If you would like to update the database with the content of a JavaScript variable, you will need to make a new request to the server. This can be a redirect, AJAX, socket, etc. But putting PHP inside of your javascript expecting it to execute like this just doesn't work.
Just a side note, this will work the other way around since PHP is executed first. This does not help your question, but might help clarify why your code isn't working:
This will work:
<script>
alert("<?php echo $variable; ?>");
</script>
After reviewing everything you all said to me I was able to think of a simple solution:
Heres the new javascript:
<script type="text/javascript">
function checkFinished(){
if(end()){
document.getElementById("setScore").value = score;
gameover = false;
}
}
</script>
added a simple form:
<form name="highscore" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<input id="setScore" name="setScore" value="" type="submit" />
</form>
then some php
<?
if(isset($_POST)){
if(isset($_SESSION["id"])){
$id = $_SESSION["id"];
$score = $_POST["setScore"];
$userName = $id["name"];
$update = "UPDATE bloodred SET score='$score' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
}
?>
Thought id post this in case anyone else needed it. Thanks again guys for your help!
Without using ajax you can create an iframe and post to it using a form on the page with the target attribute.
javascript
function checkFinished(){
if(end()){
var iframe = document.getElementById('updateScore'),
form = document.createElement('form'),
input = document.createElement('input');
if(!iframe){
iframe = document.createElement('iframe');
iframe.name = 'updateScore';
iframe.id = 'updateScore';
}
input.name = 'score';
input.value = getGameScore();
form.action = '/updatescore.php';
form.method = 'post';
form.target = 'updateScore';
form.appendChild(input);
form.submit();
form.remove();
gameover = false;
}
}
updatescore.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['id']) && isset($_POST['score'])){
$id = $_SESSION["id"];
$score = $dbh->real_escape_string($_POST['score']);
$userName = $id["name"];
$update = "UPDATE bloodred SET score='$score' WHERE name='$userName'";
$update = $dbh->prepare($update);
$update->execute();
}
?>
First of all: AJAX is Javascript.
Second: PHP is a Server-Side language. Javascript a Client-Side. So what you want mixing PHP code with JS code will never work. When JS execute, all PHP code was already evaluated and executed by PHP compiler.
To solve your problem there are some methods,like:
You could use HTML5 WebSocket, but this is kind of AJAX and the user must have a updated, newer, browser and you must implement de server side of PHP socket to listen the user gameover event (too much resources of the server).
You could use AJAX (since AJAX is Javascript), is the fast, easy and recomended.
You could redirect the user, when the game over, to another page (or the same, this is your logic) passing a querystring or a cookie with the new score, doing this the PHP code can take the updated and correct value of score and update the database.
Just remember that all forms listed above are insecure because run in client-side and so, any client (AKA user/player) can change the value of score for whatever he wants.
If you cannot use AJAX (again, AJAX is Javascript), if you cannot use WebSockets (Server limitation or HTML 5 limitation), you could load a PHP through a script tag or a iframe tag (but don't tell anybody that was me who told you do that haha)
<script type="text/javascript">
var score = getCurrentScore(); //a simple method that returns the current user score to be stored in database
function updateScore()
{
var s = document.createElement("script"); // create a tag script via JS
s.scr = "updateScore.php?score=" + score + "&nocache=" + Math.floor((Math.random()*1024)+1); // determine that source of this script is the url of script that updates the score for current user, with the queryString score value. nocache querystring with random value between 1 and 1024 is just to guarantee that the script will be loaded every time and not a cached version of a file will be acessed. For better results add a HTTP header "expire" in the updateScore.php with a small or negative value.
s.type= "text/javascript"; // type of script (make sure that updateScore.php response a content-type text/javascript e a valid or empty javascript code
document.getElementsByTagName("head")[0].appendChild(s); //append the tag script at the end of tag head of the current page
}
// call updateScore() method when user gameover!
</script>
When you call the method updateScore it will produce something like:
<script type="text/javascript" src="updateScore.php?score=1000&nocache=123"></script>
This is similar a AJAX request, or a direct request or direct access to the file. Where score=1000 represents a score with value 1000 and nocache=123 is a random value just to guarantee the fresh load of file. (calling method again, nocache value /probably/ will change to something different than 123...)

How to access variable declared in PHP by jquery

For example i declare some variable like test in server side of my PHP
echo('var test = ' . json_encode($abc));
Now i want to use this test variable in Jquery ..how can i use it?
What function do i need to use it?
For Example i have:
I have back end PHP code something like this
$abc = no
echo "var test= ".json_encode($abc);
I want jquery to do the following action(client side)
$(document).ready(function(){
function(json) {
if($abc == no )//this i what i want to be achieved
}
}
I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify.
for example:
<?php
$result = array('abc' => 'no');
echo json_encode($result);
?>
This is serverside script called data.php. In Javascript you can make so:
$(document).ready(function(){
$.getJSON('data.php', function (data) {
if(data.abc === 'no') {
your code...
}
});
}
You're comparing the wrong variable:
<?php
echo <<<JS
<script type="text/javascript">
var test = {json_encode($abc)};
$(document).ready(function(){
if(test == 'no' )
// here you go
}
});
</script>
JS;
If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:
<script type="text/javascript">
var phpValue = <?php echo $abc; ?>;
alert(phpValue);
</script>
I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:
<script type="text/javascript">
var phpValue = no;
alert(phpValue);
</script>
This is very basic, but you get an idea of what you could do by using that kind of code.

Categories

Resources