Passing a SESSION variable to JS - javascript

Okay, here's something that may seem rather trivial, but it's been giving me a headache, and I must have some sort of mental block now.
I want to pass a SESSION variable into JS, and then ultimately onto another page... It's only the first part that I'm worried about for now, because I can't even get a good "alert". The variable is blank... "the page at xxxxx says ____", even though the username shows up in the HTML span tag.
So, here's the applicable code on my page.
EDIT - For those asking why I would do this, I read it on (this) post...
EDIT: Solved. The method to do this is best done with:
var player = "<?php echo $_SESSION['username']; ?>";
Didn't need jQuery or other code. It is simple and direct, and shame on me for just sticking with one proposed solution from the other post.
In answer to some other questions: I did already have start session() at the top of the file. The script was after the HTML/PHP code. ***
... HTML stuff...
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
...more HTML...
<script>
function rollpublic()
{
... some declarations...
var player = document.getElementById("username").innerHTML;
alert (player);
more JS }
</script>

Edit
Sidenote: One reason which may be the cause of your session name not appearing, may be because session_start(); is not present in your pages, nor is there any mention of it in your posted code.
Without seeing FULL code, is hard to pinpoint it.
However, here is a successful test that I performed using the following codes: (page 1 & page 2)
Page 1:
<?php
session_start();
$_SESSION['username'] = "USERNAME";
?>
Check session name
Page 2: (sessions_check.php) which will echo and alert the session name.
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var player = "<?php echo $_SESSION['username']; ?>";
alert (player);
});
</script>
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
Appearing in HTML source: var player = "USERNAME";
and You are <span id='username'>USERNAME</span></div>
N.B.: session_start(); needs to be inside all of the pages using sessions in order for this to work properly.
(Original answer) This worked for me:
<?php
session_start();
$_SESSION['username'] = "USERNAME";
?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var player = "<?php echo $_SESSION['username']; ?>";
alert (player);
});
</script>
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>

You may call session by ajax:
function getSession(){
var session;
$.get('someUrlThatReturnSession', function(sessionData) {
session = sessionData;
});
return session;
}

You can assign SESSION variable to javascrip variable..
<script>
function myFunction(){
var a = <?php echo $_SESSION['var'] ?>;
alert(a);
}
</script>
If you need more help let me know..

If you're using Angular JS, you can use this approach. (Provide the PHP var to the ng-init param of a hidden input)

Related

Get Json_encode to a different jQuery page

I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).
Here is my process.php file:
<div id="msg" class="msg">
<?php
$query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
$json = array();
$result= $conn->query($query);
while($row = $result->fetch_assoc()){
$json[]= $row;
}
echo json_encode($json);
?>
</div>
This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.
Here is my jQuery file:
<script>
$(document).ready(function(){
$("button").click(function(){
var mycontent = $('div.msg').text();
console.log(mycontent);
});
});
</script>
But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?
You need to make AJAX call to the process.php page. Try the following code:
`<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax( {
type : 'GET',
url:'process.php',
success:function(mycontent) {
console.log(mycontent);
}
});
});
});
</script>`
If you have a single page application and when you say page you mean hidden/displayed content, your code should work. But if you have actual pages, this will never work because your source div does not exist in the DOM once you have switched pages

External php file that is loaded into index.php with .load() method not recognising $_SESSION variables

So my main page loads other php pages into it with click of a button so it can be a single page website without having to load all the content at once.
index.php
<?php
session_start();
?>
<head>
$('#btnPetShop').one( "click", function(){
$( "#page_shop" ).load( "shop.php" );
});
</head>
<body>
<?php
echo session_status();/----Always returns 1, no matter if logged in or not----/
if(isset($_SESSION['admin']))
{
if($_SESSION['admin']==1)
{
/----this part works, I am logged in as admin----/
}
}
?>
<div id="page_shop"></div>
</body>
shop.php
<?php
if(isset($_SESSION['admin']))
{
if($_SESSION['admin']==1)
{
}
else{}
}
else{} <----I end up here as if $_SESSION['admin'] is not set----/
/----code entered here loads fine----/
?>
The idea is to make a delete and edit button (if you are logged in as admin) on every article in shop.php.
Problem is that $_SESSION['admin'] is recognized on index.php, but not inside shop.php
I tried typing the content of shop.php directly into and it works, the problem is that i want it to load with a click of a button.
Where ever ( in any PHP page) if you want to use any Session variable then you have to first declare session_start(); so, in your case if you have $_SESSION['admin']="User1234" on index.php and if you want to use value of $_SESSION['admin'] in shop.php then you have to again declare session_satart(); and then use it. For example, If let consider that index.php has session variable $_SESSION['admin']="User1234" and now you want to print "Welcome User1234" on shop.php then you can do it as shown below.
index.php
<?php
session_start();
$_SESSION['admin'] = "User1234";
?>
Shop.php
<?php
session_start();
echo "Welcome, ". $_SESSION['admin']
?>
Output:
Welcome, User1234
You need to add session_start(); in each page that needs access to the session data.
See: http://php.net/manual/en/function.session-start.php
EDIT
Since the solution mentioned in my original answer does not work for you and session_status() returns 1 in your code, it means sessions are enabled on your server. There is only one thing left which could explain that your sessions are lost:
You are loading shop.php with an AJAX request, is the URL exactly in the same domain as index.php? Try to add the full path before shop.php to see if this solves the issue.
Just to be clear, if your index.php runs on http://localhost/test/index.php, your new code will be:
$( "#page_shop" ).load( "http://localhost/test/shop.php" );
Well okay, I feel dumb... I found the solution.
I had this as a script
$('#btn_logout').click(function(){
<?php session_destroy();?>
});
This is a big no no and if you do this you should be ashamed

Change href depending on php response

I want to change the href of morestorieslink depending on the data received from mysql database i.e. if there is no row returned from server then the href for DOM element morestorieslink should change
I am using this for changing the href value
if (mysql_num_rows($result) == 0) {
?>
<script type="text/javascript">
document.getElementById("morestorieslink").href="select.php?<?php echo $selecturl?>=<?php echo $select; ?>&select=Continue";
</script>
<?php
echo "Url Changed";
}
In this case javascript doesn't work but the echo is displayed, I also tried embedding javascript inside php echo.
Thankyou
if (mysql_num_rows($result) == 0) {
?>
<script type="text/javascript">
// wait for dom to finish loading properly.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("morestorieslink").href="select.php?<?php echo $selecturl?>=<?php echo $select; ?>&select=Continue";
});
</script>
<?php
echo "Url Changed";
}
Put this at the last of your page make it a point that no java script is executed after this. Rest all looks good.
Hope that helps.
Note :
the href you mentioned will append to the exsisting url.
Also check that $selecturl or $select is not null and isset.
You can also check the page source to check wether the link is generating properly or not (using Firebug in mozilla)
you can use ternary operator. Something like:
<?php echo $select ? $selecturl.$select : $otherURL;?>
I assumed your url is changing based on value of $select

Why yii captcha always shows a fixed picture?

Captcha works with no problem, but I have no idea why it's not generating a new code to dislay? I've looked into the documents but could find something that could solve my problem.
Is there something here that I'm missing. thanks.
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
my view file:
<?php echo $form->labelEx($model,'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
<?php echo $form->error($model,'verifyCode'); ?>
This is a known bug, that would most likely be fixed in Yii2.
On the Yii forums, user Black suggests:
My solution was to remove the session key on my controller action on get. Be careful not to remove it in any other place because it will probably fail on server validation.
$session = Yii::app()->session;
$prefixLen = strlen(CCaptchaAction::SESSION_VAR_PREFIX);
foreach($session->keys as $key)
{
if(strncmp(CCaptchaAction::SESSION_VAR_PREFIX, $key, $prefixLen) == 0)
$session->remove($key);
}
Another way to workaround would be to use JavaScript to click on the refresh link on every page load as mentioned by Soph:
$(function() {
$('#yw0_button').click();
});

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

Categories

Resources