How to clear a PHP session using Jquery/Javascript? - php

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

Related

How can I session destroy when user close the page?

These codes work but when I click somewhere (link or button), redirected to logout.php
var s= 0;
jQuery(function(){
jQuery(window).bind('beforeunload', function () {
if (s == 0) {
$.ajax({
async: false,
url: 'logout.php'
});
}
s++;
});
});
You could put in your session a variable with time() inside and use it as a short expiry limit, and while the user is inside your page do continous ajax calls to a php that updates the expiry. At the top of your page put:
session_start();
if(isset($_SESSION['expiry']))
if(time() > $_SESSION['expiry']){
session_destroy();
header("Refresh:0");
die();
}
$_SESSION['expiry'] = time()+20;
keep_alive.php
session_start();
$_SESSION['expiry'] = time()+20;
And in your js ping keep_alive.php with ajax every 10 seconds. If the user closes the page and doesen't rapidly reopen it loses his session

Calling Php Function With Ajax Request to change session variable

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

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

Add Redirect URL link to JS Function

How can I add redirect URL link to JS function (example form action to : session.php) in below code.
I've tried with another way code, but it still can't function.
$(document).ready(function() {
$("#submit_butt").click(function() {
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Invalid username or password!</p>');
// clear the fields to discourage brute forcing :)
$("#password").val("");
document.forms['login_form'].elements['username'].focus();
});
});
You can try this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
https://developer.mozilla.org/en-US/docs/DOM/window.location
Ref: How to redirect to another webpage in JavaScript/jQuery?
you can use this..
window.location.href = "http://www.google.com";
you can try
<script>
function name(){
window.location ='abc.php';
}
</script>
you can by breaking into php code inside your javascript
$(document).ready(function()
{
<?php
someFunction();
?>
});
but only if your javascript is in a php file so it can be processed by php. So if your linking to a .js file that needs to be changed to .php

php, how to call a javascript function?

i am trying to use gigya auth properties to login users on my website. They have a function that needs to be called after i authenticate the credentials as seen in this illustration
I have a form and when i submit the form i send it to login.php where i authenticate my users. My question is how do i call socialize.notifyLogin?.
this is the javascript:
<script type="text/javascript"> var conf = { APIKey:'2_9E9r_ojXEqzZJqKk7mRqvs81LtiSvUmBcm' }; </script>
<script type="text/javascript">
var secret = 'eIqtclW2CxC6qvmT55MvOxZ5Rm7V5JhBV/gioJLKIxM=';
var yourSiteUid= '<?php echo $talentnum;?>'; // siteUID should be retrieved from your user management system
function your_b64_hmac_sha1(secret, datePlusSite) {
var b64Sig = ''; // Place your implementation here ...
return b64Sig;
}
function printResponse(response) {
if ( response.errorCode == 0 ) {
alert('After notifyLogin');
}
}
var dateStr = getCurrentTime();
var datePlusSite = dateStr + "_" + yourSiteUid;
var yourSig = your_b64_hmac_sha1(secret, datePlusSite);
var params={
siteUID:yourSiteUid,
timestamp:dateStr,
signature:yourSig,
callback:printResponse
};
gigya.services.socialize.notifyLogin(conf,params);
</script>
to be more clear i set the $talentnum; inside my login.php. so i have the form i send it ti the login.php and a redirect page... Where the call to socialize.notifyLogin will be?
thanks,
any idea helps
You have two options:
If you call login.php as the target of an HTML form, you should redirect the user to a new HTML page upon successful login. This new HTML page should contain the socialize.notifyLogin call.
If you call login.php via an AJAX request, you should call socialize.notifyLogin in the "success" callback of the AJAX request.
In no case, however, will you be able to execute the Javascript function directly from your PHP script. PHP executes on the server before the Javascript is sent to the user as output with your HTML document, and therefore cannot execute Javascript functions directly.
PHP is executed before the page loads, therefore you cannot call a JavaScript function from PHP.

Categories