I've got a simple jQuery function and at a certain point (let's say on a button click) I'd like to start a PHP session.
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//here I'd need a way to trigger the session.
});
});
I would assume starting a session from PHP can be done as easily as changing a PHP variable. For example - the PHP can be something like:
<?php
$testVar = null;
if(isset($testVar)){
session_start()
$_SESSION['sessionStarted'] = $testVar;
}
?>
Is there a way for such as session to be started?
<?php
session_start();
if(isset($_GET['login'])) {
if(isset($_SESSION['sessionStarted'])) {
echo 'session is already set';
} else {
$_SESSION['sessionStarted'] = $testVar;
}
}
?>
and client-side:
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//code to redirect to index.php?login=true or make some ajax GET call, doesnt matter
});
});
then you can add like php checks, if session exists, do not echo loginPopupButton and so on :)
Related
How to store PHP session variable in JQuery variable.
I have one php file where i am using session variable as
$local_session = $_SESSION['sessionusername'];
and that PHP falls also using one .js file where i want to store this $local_session which is PHP variable to JQuery variable
It is as
session_start();
ob_start();
if(!$_SESSION['sessionusername'])
{
header("location:index.php");
}
else
{
include ('connection2.php');
include('PHP/combo_val.php');
$local_session = $_SESSION['sessionusername'];
}
and after this my HTML code starts
You might do something like this in your java script:
var sessionVar = '<?php echo $local_session; ?>';
and then use this global JS variable wherever in your page.
You can write some php-script which return session data, for example
JS:
//my.js
$.getJSON( "myssesiondata.php", function( data )
{
console.log(data);
}
PHP:
<?php
//mysession.php
return json_encode($_SESSION);
?>
# Axel Amthor
My JQuery Code is as
var lgn_usr = '<?php echo $_SESSION["sessionusername"] ?>';
alert(lgn_usr);
and it display
<?php echo $_SESSION["sessionusername"] ?>
as message
# Axel Amthor
My Jquery file code is as:
$(document).ready(function() {
$('#submit').click(function() {
submit_fxn();
$('#form_nuser').submit(function(e) {
return false;
});
});
function submit_fxn(){
var check_flag = 0;
var lgn_usr = '<?php echo $local_session; ?>';
alert(lgn_usr);
};
});
OKay, I got it. $_SESSION is a PHP array, we cannot set it on the client side via Javascript. The value has to be sent to the server to be stored in the array. Now, I am going for other method....
This php function currently redirects the user to another page if they aren't logged in
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
header("location: login_failed.html");
exit();
}
How can I change the function so that instead of redirecting the user it does the following:
Triggers the javascript function: loginFailed();
Prevents specific iframes which are preloaded from launching (these require a user to be logged in, and are currently opening as empty iframes if they're not logged in). I've included the script for this below. Alternatively, preventing iframes from launching which have a specific class or data-fancybox-type, or those which require !isset($_SESSION['SESS_USER_ID']).
The functions which I want to trigger/prevent
function loginFailed() {
$().toastmessage('showToast', {
text: 'Log In Failed<br/><br/>Please check your username and password',
sticky: false,
position: 'top-center',
type: 'message',
closeText: '',
close: function () { console.log("toast is closed ...") }
});
}
$(function () {
$(".fancybox").fancybox({
preload: true,
});
$(".fancybox").eq(0).trigger('click');
});
I've tried:
echo "<script>loginFailed();</script>";
echo "<script type="text/javascript">loginFailed();</script>";
echo "<script type="text/javascript">loginFailed;</script>";
Adding on to techfoobar's answer...
It is generally a good practice to put your variables from PHP into Javascript (if needed) and letting Javascript handle it, as opposed to echoing different javascript depending on a PHP variable.
Keep in mind that all javascript variables CAN be manipulated by the client.
Try something like this:
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
$t="no_session";
}
else{
$t="yes_session";
}
....
<script>
var session="<?php echo $t; ?>";
if(session == "no_session")
loginFailed();
</script>
PHP runs on the server side. JavaScript runs on the client side inside the browser. PHP cannot directly invoke JavaScript functions.
PHP can however render JavaScript along with the HTML to the browser so that the browser can in turn run it.
In your particular case, one thing you can do is check for logged-in status via an AJAX call and call the required JS methods on its success callback.
Example:
For checking the login status:
/* JS */
function checkLoginState() {
$.post('/yourserver.com/isloggedin.php', function(data) {
if(data != "OK") { // not logged in
// call your JS method thats disables stuff etc.
loginFailed();
}
});
}
// Periodically check login state
setInterval(checkLoginState, 10000); // check every 10 seconds, change as needed.
/* PHP - isloggedin.php */
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
echo "NOT OK";
}
else {
echo "OK";
}
I combined #hellohellosharp's suggestion with a solution which was given to me by #willoller for another problem and figured it out :-)
Add this to the php:
$logged_in = (isset($_SESSION['SESS_USER_ID']));
Add this to the javascript:
<?php if ($logged_in) : ?>
<a class="fancybox" data-fancybox-type="iframe" href="iframe1.html"></a>
<?php else : ?>
loginFailed();
<?php endif; ?>
I'm also using this to change the menu options based on whether or not a user's logged in.
Just a reminder - this uses ISSET to determine what javascript should show, but it only changes the user's experience and doesn't provide any security.
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
Session is client side staff, but is it possible through clear it using javascript code?
I would like too have the idea like this and ,can it convert to jquery format? Thank you.
js
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
$.post("clear.php",function(data){
});
});
});
php
<?
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_POST['creminder']))
unset($_SESSION['creminder']);
?>
Is this one ok ?
make an ajax call to the server and let your server page kills/ends the session
HTML
<a href="#" id="aKill" > Kill Session</a>
Script
$(function(){
$("#aKill").click(function(){
$.post("serverpage.php",function(data){
// if you want you can show some message to user here
});
});
and in your serverpage.php, Execute the PHP script to terminate the session.
Create a separate file to clear the session only. clearsession.php
session_start();
session_destroy();
Now, make a simple request
$("#aKill").click(function(){
$.get("clearsession.php");
}
The below covers the basics more or less.
The Function:
function destroySession(){
var theForm = $("#yourForm");
//we don't need any ajax frame.
theForm.each(function(){ this.reset() });
$.ajax({
url: 'destroysession.php',
type: 'post',
data: 'sure=1', //send a value to make sure we want to destroy it.
success: function(data);
alert(data);
}
});
}
The PHP (destroysession.php):
<?php
//whatever logic is necessary
if(!empty($_POST['sure'])){
$sure = $_POST['sure'];
if($sure == 1){
//logic to destroy session
echo 'Session Destroyed!';
}else if($sure != 1){
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
}else{
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
?>
The HTML:
<input type='button' value='reset' onclick='destroySession()'>
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
In an ExpressionEngine template, I'm setting a PHP session variable in a javascript file like this: (Yes, EE will parse the PHP and add plug the values to the javascript)
<?php session_start(); ?>
function check_someone_else_result(data) {
waiting_list_flag = false;
<?php $_SESSION['waiting_list_flag'] = false; ?>
if(data.CanBuy=='YES'){
show_for_someone_else();
} else {
waiting_list_flag = true;
<?php $_SESSION['waiting_list_flag'] = true; ?>
$('#sm_content .oblcontent').html($('#waiting_list').html());
$('#sm_content a.closebtn').click(function(){location.reload(true);});
$('#sm_content a.yeswaitbtn').click(function(){show_for_someone_else();});
} // if(data.CanBuy=='YES')
} // function check_someone_else_result
Now, in the show_for_someone_else() function, I'm redirecting to another page that loads another javascript file and I'm trying to set a javascript variable to the same value that I set the session variable to above.
<?php session_start(); ?>
var CART_URL = '{site_url}store/checkout/cart/';
$(document).ready(function(){
// attach the validationEngine to the form
$("#voucher_form").validationEngine('attach', {
scroll: false
}); // $("#voucher_form").validationEngine
// handles the NExt button click
$('#checkout-step-billing a').click(function(){
$('#checkout-step-billing .voucher_form').submit();
}); // $('#checkout-step-billing a').click
// handles keypresses in all the fields in the form to submit the
// form when the press enter
$("#checkout-step-billing .voucher_form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#checkout-step-billing .voucher_form').submit();
return false;
} else {
return true;
}
}); // $("#checkout-step-billing .voucher_form input").keypress
// set the wait_list_flag from the session variable
var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>
}); // $(document).ready
But I am not getting anything at all.
How do I need to do this?
var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>
should be
var wait_list_flag = <?php echo $_SESSION['waiting_list_flag']; ?>;
^^^^ ^
Without the echo, the PHP block doesn't output anything, so nothing gets inserted into the Javascript block. You're also missing the trailing semicolon in the javascript, which may also cause a fatal parse error.
To set the value, you will need to echo / print the $_SESSION['waiting_list_flag']; in the second snippet.
Keep in mind, in the first snippet, PHP will be run first (it's not run with the JavaScript), so the session var will always be true. (Unless that is what you meant wrt EE)