I have a communication problem between home.php page and user.php page.
on Homepage there is link for Log out
<span class="log_out"> <a id="logOut">Log Out</a></span>
When a user click this page ajax call will be started
Here is my ajax call
<script>
$( document ).ready(function() {
$( "#logOut" ).click(function() {
$.ajax({
url: 'class/user.php',
data: "logout=1",
success: function(data) {
$('body').append(data);
}
});
});
});
in user.php I have this
<?php
if(isset($_GET['logout'])){
echo "alert";
$_SESSION['user'] = 0;
}
?>
When I click logout, alert is being appended in body, but session variable was not changed at all.
I dont know what's going on here.
You need to add session_start(); to the top of your user.php file and also debug with the echo after a session is set, otherwise you'll get the warning you're getting at the moment.
if(isset($_GET['logout'])){
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user'] = 0;
Print_r ($_SESSION);
}
I found solution thanks for helping guys, I just need to add session validation on my if else clause, although I have this validation on top of the page, when I added it inside the function, problem fixed
Related
Page1.php (Not Full code)
<?php
class A {
function Session() {
session_start(); // assume session started here
}
?>
<button onclick="play('MyVideo.mp4',event)">MyVideo1</button
<script type="text/javascript">
function play(video,e) {
var videoFile = 'folder1/product.php?v=' + video;
$('#divVideo video source').attr('src', videoFile);
$("#divVideo video")[0].load();
}
</script>
<?php
}
?>
product.php (this page is not a class)
In product.php I am having some code, but if(isset($_SESSION)){ condition failed ,so got to understand that session getting failed.
How do I make session pass in product.php? I cannot use $this in this product.php page.
To pass data to your products.php file you would need to use ajax, then you can pass the variable from the session via ajax to your file.
At first we need to capture the session variable in hidden input
<input type="hidden" value="<?php $_SESSION['variable_name']?>" class="sessionName" >
now the js file
<script>
$(document).ready(function() {
var name = $('.sessionName').val();
$.ajax({
url : 'products.php', // url to your file could be different
type : 'post',
data : {
sessName: name )
},
success : function(data) {
console.log(data);// check console long for output and errors
}
});
});
</script>
in your products.php file
if (isset($_POST['sessName']) ){
$session_name = $_POST['sessName']
//output to console.log in case the variable is set
echo 'Session Variable : '.$session_name;
}else{
//output to console.log when variable is not set
echo 'Session Variable is not Set'; // if not
}
Hope this help.
Just want to ask if is it possible to clear a PHP session using a jquery or javascript process? Because what I want to do is to clear the PHP session using a dialog box. If the user click the 'OK' button it will process the unset function. In my page there's a checkout process and after the user click the button 'OK' it will prompt a dialog box and if the user click the 'OK' button it will unset the PHP session and it will be redirected to another page.
Here's my simple code:
<i class="fa fa-check"></i> <span id="save_registry" class="cursor: pointer">OK</span>
<div id="save_alert" style="display: none">
<?php unset($this->session->data['cart']);
</div>
....
$('#save_registry').click(function(){
$('#save_alert').dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
location = 'index.php?route=common/home';
}
}
});
});
Simply put: You can't, directly.
PHP is a server-side language while javascript is a client-side one, which means that there's no other connection between them other than the document you receive and interacts with you. The sessions are stored and managed by the server.
You can, however, as War10ck suggests, call to a server-side script that clears the session. Something like this:
PHP:
<?php
/*
* session_start();
* Starting a new session before clearing it
* assures you all $_SESSION vars are cleared
* correctly, but it's not strictly necessary.
*/
session_destroy();
session_unset();
header('Location: continue.php');
/* Or whatever document you want to show afterwards */
?>
HTML/javascript:
<script type="text/javascript">
function logout() {
document.location = 'logout.php';
}
LogoutButton.addEventListener('click', logout, false);
</script>
<button id="LogoutButton">Log out</button>
Or even performing an asynchronous call:
function logout() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
document.location = 'continue.php';
}
xhr.open('GET', 'logout.php', true);
xhr.send();
}
There is a way you can do it directly from javascript... first you have to declare a function that clears a cookie by its key
function removeCookie(cookieName)
{
cookieValue = "";
cookieLifetime = -1;
var date = new Date();
date.setTime(date.getTime()+(cookieLifetime*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = cookieName+"="+JSON.stringify(cookieValue)+expires+"; path=/";
}
Now all you have to do is to remove a cookie with the key "PHPSESSID" like this
removeCookie("PHPSESSID");
Now when you var_dump($_SESSION) you find it empty array
You can't clear a php session using Javascript directly.
PHP is a server-side language, whereas Javascript is client-side..
However, you can throw an ajax request to the specified page that handles the destruction.
Like this:
// Client-side
$.post("logout.php", {"can_logout" : true}, function(data){
if(data.can_logout)
// redirect the user somewhere
}, "json");
<?php
// Server-side
$can_logout = $_POST["can_logout"];
if($can_logout)
session_destroy();
echo json_encode(array("can_logout" => true));
?>
Or just point the user to some page that handles the session destruction; i.e. logout.php
I have the message-block in the header of my site. When a user clicks "close msg", the message should disapear and can't be seen during current user session.
So I decided to use jQuery Ajax:
$('#lang-msg .close').on('click', function(event) {
event.preventDefault();
$.ajax({
url:"remlmsg.php",
type:"POST",
data:"id=2,myajaxquery=true ",
success:function(html){
console.log(html);
$('#lang-msg').fadeOut(300,function() {
$(this).remove();
})
}
})
})
And in remlmsg.php I have only code, which defines new session variable:
$_SESSION['langmsg'] = 'hide';
echo $_SESSION['langmsg'];
In the header.php file I check if $_SESSION['langmsg'] is undefined.
if (!isset($_SESSION['langmsg'])) {
if ($sLanguage == 'ru') {
echo '<script type="text/javascript">
$( function() {
showLangMessage("en");
})
</script>';
}
}
And it says always true! But when I print request data in ajax function it displays 'hide'.
Explain to me, please, where I did mistake.
P.S.
Tested on local server (latest WAMP)
You need to have session_start() declared first. Otherwise you'll only edit a local variable that isn't stored anywhere.
Actually the problem you're having is that ajax calls will have a different session id, which has to do with the headers sent/received by both sides.
Try generating some javascript with PHP like:
var phpSessionId='<?=session_id()?>';
then in your remlmsg.php add this to the very top:
if(isset($_POST['session-id'])) session_id($_POST['session-id']);
session_start();
Finally in your ajax call use:
data:"id=2,myajaxquery=true,session-id=" + phpSessionId,
That should solve your problem.
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
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()'>