I have this website where I can interact with the web both as a logged or anonymus user. When I click a link I call an ajax function:
you click here:
<a id="alcrearuta" class="'.$row->urlamigable.'" href="#">aƱadir a ruta</a>
This is my ajax function:
var valor=$("#alcrearuta").attr('class');
$("#alcrearuta").click(function(){
$.ajax({
type: "GET",
url: "../ajax/ruta.php",
data: "urlamigable=" + valor,
dataType: 'html',
success: function(data) {
$("#listaruta").html(data);
}
});
});
The thing is I have two possibilities: either a logged user clicks the link and the ruta.php does its stuff on the database considering the userid that's set in the session or I have an anonymous user that wants to do something similar.
In my ruta.php I have:
if(!empty($_SESSION['Username'])){
//Insert stuff on DB
}else{
//I wish I could create the session here but I can't since it's an ajax call
}
What I need is at some point between the click in the link and the end of the ajax function I can set my $SESSION['Username'] variable to get a new value (since the user it's not logged in, it's currently empty and thus my inserts on the database not working)
if you want to use sessions in php, your php script (ruta.php) schould start with
session_start();
from that point you can assign any variable to $_SESSION['Username']
$_SESSION['Username'] = something_to_generate_a_Username;
Just like any other server request.
You could use jquery cookie library to create a session cookie.
$.cookie("Username", "NOTLOGGEDINUSER");
https://github.com/carhartl/jquery-cookie
http://www.electrictoolbox.com/jquery-cookies/
and in beforeSend for Ajax, you can check if username cookie exists, other wise, create the cookie with "NOTLOGGEDINUSER"
Maybe on the click do another AJAX call just to set the SESSION?
Related
I have a view function which only logged in user can see. When clicking the view button, it will send an ajax request to PHP function and return back the result which then be displayed in the html. The issue is, if the user idle for too long, when they suddenly come and click the view button again, the display (where the ajax response supposed to be displayed) will show the login page instead of the requested data.
It was because the PHP session has expired. I want to prompt an alert to tell them about this timeout session and redirect them to the login page instead but I don't know how to do that cause I tried to console.log() the PHP session and it's still showing all of the session. I am convinced that this is something like a memory or a flash cache (not very sure).
QuickView = (pc_no) =>{
$.ajax({
type: 'get',
url: '<?= $ajax_url; ?>view-receipt/'+pc_no,
data: { pc_no:pc_no },
success: function(res){
console.log(<?= json_encode($this->session->userLogged); ?>)
<?php if($this->session->userLogged){ ?>
$('#receipt-inline-view').html(res);
<?php } else { ?>
if(alert('Your session has expired. Please re-login.')){
window.location.href = '<?= base_url(); ?>';
}
<?php } ?>
}
})
}
Based on the code above, the user session will be stored in $this->session->userLogged. After PHP timeout, it should be cleared. But from console at ajax there, it's still showing the session even after it gets cleared up. Hence, the redirection also cannot be triggered.
On each page I check if the user is connected (i.e.: if the user session is active or not).
validateSession();
function validateSession() {
if (!isset($_SESSION['CurrentLogged_USR_Id'])) {
header("Location: 'http://example.com');
}
}
It's working.
But if the user is on a page from a long time and the system needs to make an ajax call, the same check is done but do not redirect the user.
Why ?
I've include the validateSession() on my php page called by ajax but the redirection is not make.
Thanks.
You cannot redirect in PHP that is called through AJAX. Rather return a flag that identifies that session has expired and make redirection in JavaScript.
Below is sample code snippet.
$.ajax({
url: "urlToAJAX.php",
success: function(isSessionExpired){
if(isSessionExpired)
{
window.location = "http://example.com";
}
}});
You can follow this code.
Ajax
$.ajax({
url:..
type:..
success(data){
if(data == "SESSION_EXPIRED"){
window.location = "your-login-page";
}
}
});
In your PHP code, you have check if the session is available. If not echo the string SESSION_EXPIRED.
I know that this is a question asked several times but I have search a lot to find a solution with no luck. Some of the URLs i have visited were:
https://xpapad.wordpress.com/2010/06/19/preventing-session-expiration-with-ajax/
Prevent session expired in PHP Session for inactive user
PhP Session does not refresh using AJAX
Refresh PHP SESSION var after AJAX request
Most of them suggest that in order for the SESSION to refresh you must place an AJAX request that is targeting a PHP script that starts a session:
window.setInterval( function() {
$.ajax({
cache: false,
type: "GET",
url: "refreshSession.php",
success: function(data) {
}
});
}, refreshTime );
In the refreshSession.php you can do something like session_start() .
Unfortunately by doing this the SESSION does not refresh. Any ideas why?
PS: Before calling session_start() i am calling my custom session name like session_name('CUSTOMSESSID').
Thanks,
Christos
I want to clear the php session array every time a user leaves my page, but my page has links with query strings. I don't want to clear the session array, when a user clicks on a link with a query string. I have tried the following javascript code but it does not work when the user leaves the page.
somepage.php
var url = new RegExp(/somepage.php\?sort=.*/);
if (url.test(document.location.href)){
//do nothing
}
else {
$(window).unload(function(){
$.ajax({
url: 'clear_session.php'
});
});
}
Calling a webserivce onunload is very unrealiable. Why not just unset the PHPSESSID cookie? This wont clean up the session on the server, but it will give the user a new empty session when he visits again.
I'm creating a Helpdesk system, sometimes a user get more than two hours without using the system and then return when the session has expired, but the last loaded page remains on the screen (a form, for example) and the user can use it normally, but when he submits the form he is redirected to the login page (it's ok), but the user loses data entered.
I want to create an AJAX function that checks if the session has expired or not. That function should be performed using setTimeout() or setInterval().
I've tried using the "sess_expiration" but it seems that this value does not reset on page load, i.e. after ending the appointed time (7200 by default) it forces the session expiration.
You can do it like this
$.ajax({
type : 'POST',
url : '<?php echo site_url('controllername/methodname')?>'
success : function(data){
if(data){
//session available
}else{
// expired
}
});
And controller method
function methodname(){
$user_id = $this->session->userdata('user_id');
if($user_id){
echo 1;
}else{
echo 0;
}
}
You can wrap ajax request in function and return the result everytime with TRUE or FALSE. Moreover setInterval can call this function for checking session.
Codeigniter session class has method which let us know about session expiry.
function your_method(){
$this->session->sess_read() === false ? echo "0" : echo "1";
}