Session Flag doesn't work in Javascript - php

I use session flag in javascript for IF function. If session flag is 1, the javascript will show a specifict div on click. I have tried it manually, but the code doesn't seem to work.
This is my JS code:
$(document).ready(function(){
check = <?= $_SESSION['flag'] ?>;
$("#bag").click(function(){
if(check==0){
$("#login").show();
$("#notlogin").hide();
} else {
$("#login").hide();
$("#notlogin").show();
}
});
});
And this is the session in the head of html file:
<?php #session_start();
$_SESSION['flag']=0;
?>
Please check it in the fiddle: http://jsfiddle.net/9mm5ougu/
config-haslogin.php
<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
mysql_connect("mysql.com","name","password") or die("cannot connect");
mysql_select_db("databasename") or die("Fail here");
$myemail= $_POST['myemail'];
$mypassword= $_POST['mypassword'];
$sql= "SELECT * FROM user WHERE myemail='".$myemail."' and mypassword='".$mypassword."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
echo "Login successful";
$_SESSION['flag']=0;
header("Location:index.php");
}
?>

You can't put PHP code into a JavaScript file, because PHP is interpreted on the server side, while JavaScript is interpreted on the client side (at least here in your use case).
If you really have to do conditional treatment based on the PHP $_SESSION value, you have multiple choices (listed from the worst to the best one IMHO):
Solution 1: use a dynamic JavaScript file (the worst)
Put PHP code in your JavaScript file, but use the .php extension instead of .js. Your JavaScript code would look like something like this:
file.js.php
$("#bag").click(function(){
<?php if ($_SESSION['flag'] === 0): ?>
$("#login").show();
$("#notlogin").hide();
<?php else: ?>
$("#login").hide();
$("#notlogin").show();
<?php endif; ?>
});
And you can include this PHP file as a JavaScript file:
index.php
<script src="file.js.php"></script>
This is the worst solution:
- as you're mixing both languages, your file will soon become unreadable
- because the file is now dynamic, the user's browser can't put it on the client-side cache
- you're using PHP server's resources where it's not really necessary
- you can't deploy your file on a CDN, or on a simple server dedicated to serve static file
- you can't minify your JavaScript file
Solution 2: use two different JavaScript files
Create two different JavaScript file, one for logged in user and one for logged out. Load the correct file using the $_SESSION value.
loggedOut.js
$("#bag").click(function(){
$("#login").hide();
$("#notlogin").show();
});
loggedIn.js
$("#bag").click(function(){
$("#login").show();
$("#notlogin").hide();
});
index.php
<body>
<!-- page content here -->
<?php if ($_SESSION['flag'] === 0): ?>
<script src="loggedIn.js"></script>
<?php else: ?>
<script src="loggedOut.js"></script>
<?php endif; ?>
</body>
This solution is better than the first one because it resolves almost all points: the file is cached on the client and you don't mix PHP and JavaScript code. But this is not the best solution you can have, because it brings a lot of code duplication and it would be harder to maintain the code base.
Solution 3: bring the model client side (or sort of)
You can pass your data model to the JavaScript file, and use it directly from there. As an example, you can have a class name on the <body> tag that depends on the $_SESSION['flag'] value, and your JavaScript file will behave differently based on this value. Here is an example:
index.php
<?php
$className = $_SESSION['flag'] ? 'logged-in' : 'logged-out';
?>
<body class="<?php echo $className; ?>">
<!-- page content here -->
<script src="yourFile.js"></script>
</body>
yourFile.js
$(document).ready(function(){
var isLoggedIn = $('body').hasClass('logged-in');
$("#bag").click(function() {
if (isLoggedIn)
{
$("#login").show();
$("#notlogin").hide();
}
else
{
$("#login").hide();
$("#notlogin").show();
}
});
});
If this class is only used by the JavaScript code (it means this class will no be used in the CSS code), you should prefix it with this js- to differentiate it from real CSS class names.

While you are accessing PHP variables inside Javascript, enclose that within quotes like
check = "<?= $_SESSION['flag'] ?>";
Check this fiddle.

Use AJAX to get the data you need from the server.
For example create get-data.php:
<?php #session_start();
_SESSION['flag'] = 0;
json_encode(_SESSION['flag']);
?>
Call it from ajax:
$(document).ready(function(){ // your DOM loaded
$.ajax({
url: '/get-data.php',
success: function(response){
$("#bag").click(function(){
if(JSON.parse(response) == 0){
$("#login").show();
$("#notlogin").hide();
} else {
$("#login").hide();
$("#notlogin").show();
}
});
},
error: function(){
alert('data not loaded');
},
complete: function(){
}
})
})

Related

Resetting a PHP $_SESSION array with jquery function

I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions

Execute PHP Session from within JS Function

I would like to set a PHP session without reloading the page when a user clicks a button. Ideally, the button click would immediately hide the div named download_div and would set the session "close_download" to true.
I understand that JS is user-side and that PHP is server-side, but I'm wondering if there is a way to blend the two worlds. Any ideas? Thanks!
<html>
<head>
<script>
function closeDownload()
{
$('.download_div').hide()
}
<?php
session_start();
$_SESSION['close_download'] = "true";
?>
</script>
</head>
<body>
Close
</body>
</html>
session.php
<?php
session_start();
$_SESSION['close_download'] = "true";
?>
download.html
<html>
<head>
<script>
function closeDownload()
{
$('.download_div').hide()
$.get("session.php")
}
</script>
</head>
<body>
Close
</body>
</html>
You have to use ajax, read the documents on jquery ajax calls, is the fastest way.
basically you have to have another php file that has this:
session_start();
$_SESSION['close_download'] = "true";
Then in your html/js you do something like $.get('newfile.php');
You can't put php in your javascript, but using ajax you can 'blend' them as u said
The way to blend the two worlds is - AJAX.
$.ajax({
url: "session.php",
data: {'name': 'test_session', 'value': 'foobar'}
}).done(function() {
$('#notification').html('Done!');
});
session.php-
<?php
session_start();
$name = $_POST['name'];
$value = $_POST['value'];
$_SESSION[$name] = $value;
?>

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

Calling PHP from document.ready

Is there a way in document ready to call php scripts?
I want to do something like this.
<script>
$(document).ready(function($) {
<?php require("readenglish.php"); ?>
<?php require("readfrench.php"); ?>
<?php require("readspanish.php"); ?>
<?php
$opload = $_GET['opload'];
if ($opload == "reade") {
}
else if ($opload == "readf") {
echo "<script type=\"text/javascript\">\n";
echo "document.f1.r1[0].checked = false;\n";
echo "document.f1.r1[1].checked = true;\n";
echo "SelectRead();\n";
echo "</script>";
}
?>
});
</script>
The three php scripts create divs and add information to them from an external domain php script.
You're mixing client and server side with no interface there. You're going to have to use $.ajax to pull in the content from the php scripts and update your DOM accordingly.
Of course... you could also design your site in a way that makes sense. This method looks suspicious at best and almost positively has a much better, exclusively server side solution.
You could do something like this in your page:
$(document).ready(function($) {
$('#result').load('test.php', function() {
alert('Load was performed.');
});
});
Where, on the server, test.php contains your code:
<?php require("readenglish.php"); ?>
<?php require("readfrench.php"); ?>
<?php require("readspanish.php"); ?>
<?php
$opload = $_GET['opload'];
if ($opload == "reade") {
}
else if ($opload == "readf") {
echo "<script type=\"text/javascript\">\n";
echo "document.f1.r1[0].checked = false;\n";
echo "document.f1.r1[1].checked = true;\n";
echo "SelectRead();\n";
echo "</script>";
}
This then needs to be added back into the DOM on the client side. Not good design though.
I would recommend using jQuery. They have a load method that does exactly what you're asking: http://api.jquery.com/load/
you may want to read this article http://www.developer.com/tech/article.php/923111/Client-side-Versus-Server-side-Coding---Part-1.htm

<?PHP ?> tag can be used in javascript

Can we use the<?php ?> tag in javascript? If yes then my next question is; can we use session in this tag? Example:
success:function(data)
{
if(data)
{
<?php
if(isset($_SESSION['UserId']))
{ ?>
window.location.href="coll_delivery_det.php";
}
else
{
?> window.location.href="courier.php"; <?php
}
} ?>
}
If I understand what your looking to do you would want to use php to echo out your javascript commands.
success:function(data)
{
if(data)
{
<?php
if(isset($_SESSION['UserId']))
{
echo "window.location.href=\"coll_delivery_det.php\";";
}
else
{
echo "window.location.href=\"courier.php\";";
}
} ?>
}
Yes. But only if the page is executed as actual PHP page.
If you use PHP code through your javascript or HTML I suggest using templatish statements, like so:
<?php if ($someVariable) : ?>
var i = 0;
<?php else : ?>
var i = 2;
<?php endif; ?>
It'll be much more clear what statements are closed. Instead of the following:
<?php if ($someVariable) { ?>
var i = 0;
<?php } else { ?>
var i = 2;
<?php } ?>
In fact, you can't use PHP tags in JavaScript.
You can only generate either whole JS code or only some data for it using PHP.
The specific solutions posted here address your current situation, I'd just like to touch on the reasoning behind them.
Javascript logic is executed in your browser.
PHP logic is executed on the server.
Embedding conditional PHP statements directly in javascript won't do what you want, but you can use PHP to generate the javascript your browser needs to execute.
Yes as long as you are doing this within a file that will be executed as PHP but your code is syntactically incorrect from what I can see. Try this instead:
success:function(data) {
if(data) {
<?php if(isset($_SESSION['UserId'])) { ?>
window.location.href="coll_delivery_det.php";
<?php } else { ?>
window.location.href="courier.php";
<?php } ?>
}
}
It is worth noting that you cannot go the other way. Javascript variables cannot be used in PHP code as by the time the users browser executes the Javascript the PHP execution cycle is terminated. The only way to pass it back this way would be to make an Ajax request.
Also the PHP will only be run once each page load so using your code if $_SESSION['UserId'] is set then the users browser would just see:
success:function(data) {
if(data) {
window.location.href="coll_delivery_det.php";
}
}
Otherwise if it is not set it will just be rendered from PHP as:
success:function(data) {
if(data) {
window.location.href="courier.php";
}
}
In this way javascript is generated from your PHP code.
Yes, php can generate anything: html, css and JavaScript as well. So you can do something like that on your .php page:
function() {
<?php if($data) { ?>
window.location.href="coll_delivery_det.php";
<?php } else { ?>
window.location.href="courier.php";
<?php } ?>
}
However you need to remember that PHP is generating JavaScript as any other text, so you can't use Javascript variables in PHP script. eg. something like that will not work:
function test(){
var r=1;
<?php if ($r==1){ ?>
alert('r = 1');
<?php }?>
}
If you're using apache you can create a .htaccess file in your javascript directory with the following contents:
AddHandler php-cgi .js
This will make your .js files run as php, but retain its original extension.
the easiest way is to create a page that generates a dynamic javascript and includes the header for the javascript.
mysite.com/js.php
<?php header("Content-type: application/x-javascript");?>
success:function(data) {
if(data) {
<?php if(isset($_SESSION['UserId'])) { ?>
window.location.href="coll_delivery_det.php";
<?php } else { ?>
window.location.href="courier.php";
<?php } ?>
}
}
but you probably dont want to do that.. browsers save the included javascript files on cache, and you could have some problems with that..
the best way to proceed is to have your js files separated and and pass some parameter to the functions or classes using a <script> tag inside your <header>

Categories