Handle session timeout when loading data through ajax with jquery DataTables - php

My application is behind a sign in, so when loading the data through ajax, I need to verify the user still has an active session. If the user does not have an active session, I return back with echo json_encode(array('TIMEOUT')); which outputs ["TIMEOUT"]. How do I read that response and send the user back to the sign in page?
In previous versions of DataTables, I was able to do the following:
"fnServerData": function ( sSource, aoData, fnCallback, result ) {
$.getJSON( sSource, aoData, function (json) {
if(json == "TIMEOUT")
{
window.top.location.href = "/sign_out?action=to";
return;
}
fnCallback(json)
} );
Under DataTables 1.10, fnServerData has been replaced by ajax (see docs and ajax.data). How do I accomplish the same thing with the new DataTables version? I feel like I am close, but it just isn't working...possible because I am doing something wrong attempting to parse the response (I never hit inside the if statement).
"ajax": {
"url": "/account/location_load",
"data": function (myJson) {
if(myJson == "TIMEOUT")
{
window.top.location.href = "/sign_out?action=to";
return;
}
return myJson;
}
}

After a day and a half working on it, I finally found a working solution using ajax.dataSrc (doc)
"ajax": {
"url": "/account/location_load",
"dataSrc": function (myJson) {
if(myJson == "TIMEOUT")
{
window.top.location.href = "/sign_out?action=to";
return "";
}
return myJson.data;
}
I don't know why this version allowed me to read myJson and the other didn't, but it works. The working PHP code ended up being echo json_encode('TIMEOUT');

Related

How to redirect using AJAX and Jquery

I am new to Ajax and I have already seen this question but I am having this issue in chrome console
http://s2.postimg.org/6vdhlvyh5/Capture.jpg
Here's the php code...
$rs1 = [
'error' => $blank_err,
'url' => "http://localhost/experimental/view.php"
];
echo json_encode($rs1);
exit;
Here's Ajax code...
$.ajax({
type:"POST",
url:"validate_signin.php",
datatype:"JSON",
data:{
femail:femail,fpass:fpass,submit_signin: true
},
success:function(resp){
if (resp.error !== "") {
$("#err").html(resp.error);
} else {
window.location.href=resp.url;
}
and due to wrong backslashes it's not redirecting
I even tried using
$url=$_SERVER["HTTP_HOST"]."/experimental/view.php";
in php page and sending back to ajax with json_encode($rs1);
You can use JSON.parse for parsing the response and then redirecting as
success:function(resp){
var data = JSON.parse(resp);
if (data.error !== "") {
$("#err").html(data.error);
} else {
window.location.href=data.url;
}
I recommend, you can use jQuery.ajax() for this. this is easy to use and control ajax functionality. Follow this link http://api.jquery.com/jquery.ajax/

AJAX Request in CodeIgniter Application Failing After Inactivity

The application I am working on is built in CodeIgniter, and the content is always loaded via ajax into the main content div.
This works without fail normally, apart from after the user has been inactive for a short while.
We haven't completely narrowed down the inactivity time required for the request to fail, but it's around 40 minutes or more of inactivity.
I've tried logging details to the console in the error callback of the AJAX request, but nothing is logged.
I'm thinking that it's related to a session expiry but I can't be sure. I know when using CodeIgniter, there are two sessions which are created automatically (PHPSESSID, and ci_session) so my instinct is that it has something to do with these, or one of them, expiring?
When the request fails the headers, preview, response and cookies tab on chrome's developer tools show nothing.
If anyone has experienced this before, or has any ideas what may be causing the problem, I'd appreciate the input.
Edit:
Below is the AJAX request which is experiencing the above problem.
All links within my application use this loadPage function instead of a standard redirect.
function loadPage(href, type, clickElem, changeHash) {
if(ajax_loading == true) { return false; }
ajax_loading = true;
$('#recording_area').slideUp('slow');
if(typeof queue_countdown !== 'undefined') { clearInterval(queue_countdown); }
if(type == 'sidenav') {
$('#sidenav_accordion .accordion-heading a').removeClass('on');
$('#sidenav_accordion .accordion-inner a').removeClass('on');
$(clickElem).parents('.accordion-group').find('.accordion-heading a').addClass('on');
$(clickElem).addClass('on');
} else {
page_requested = href.replace(/^\/([^\/]*).*$/, '$1');
if(!page_requested) { page_requested = 'dashboard'; }
nav_elem = $('.sidenav a[href="/' + page_requested + '"]');
if(nav_elem.html() != null) {
nav_elem_group = nav_elem.parents().eq(2).children().first().find('a');
if(!nav_elem_group.hasClass('on')) {
if(!nav_elem.parents().eq(2).children().first().next().hasClass('in')) { nav_elem_group.click(); }
$('.sidenav .on').removeClass('on');
nav_elem.addClass('on');
nav_elem_group.addClass('on');
}
}
}
current_ajax_request = $.ajax({
type: 'GET',
url: href,
dataType: 'html',
cache: true,
beforeSend: function() {
},
success: function(data){
$('#map-canvas').remove();
$('.content_wrapper script').each(function(){
$(this).remove();
});
$('#gbox_Customers').remove();
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$('.content_wrapper').hide().html(data).show();
$('#content_overlay').hide();
} else {
$('.content_wrapper').fadeOut().html(data).hide().fadeIn();
$('#content_overlay').fadeOut();
}
$('.queue_loading').hide();
console.log('success ended');
},
error: function(xhr,status,error) {
/*
* The below console logs do not fire when the problem is occuring.
*/
console.log('ERROR');
console.log('xhr: ' + xhr);
console.log('status: ' + status);
console.log('error: ' + error);
$('#map-canvas').remove();
$.get('inc.404.php', function(data) {
if($.browser.msie && parseInt($.browser.version, 10) === 7) {
$('.content_wrapper').hide().html(data).show();
} else {
$('.content_wrapper').fadeOut().html(data).hide().fadeIn();
}
});
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$('#content_overlay').hide();
} else {
$('#content_overlay').fadeOut();
}
$('.queue_loading').hide();
},
complete: function(data) {
console.log(data);
ajax_loading = false;
set_tooltips();
}
});
if(changeHash != false) {
window.location.hash = "!" + href;
}
}
Edit 2:
After putting several console log's through the function, to see at which point it breaks. The problem decided to disappear. For what reason would adding console logs to the function prevent this issue from occurring?
I'm currently waiting an hour or so to re-test it without the console logs to make sure it isn't a red herring.
Edit 3:
After putting in console logs in the error callback of the AJAX request, it seems that the error callback is not firing. Not quite sure where to look now - as if it was a success, it would surely return the content.
Unsure what's causing your problem. But just in case this helps, here is a solution to a ajax and CI session problem I had.
Ajax requests would fail occasionally because the user would get logged out when the ajax request was made. (Not really sure why)
To fix the issue avoid a session update on ajax requests. To do this create a custom session class that overrides the sess_update method.
application/libraries/MY_Session.php
class MY_Session extends CI_Session
{
public function sess_update()
{
if (!IS_AJAX) {
parent::sess_update();
}
}
}
IS_AJAX is defined in application/config/constants.php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

How To Return Data from PHP to Use in jQuery(ajax)?

I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});

$.post json request doesn't return any result

Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}

Why is my json response a page full of source code

I have a simple checkbox, on click it sends XHR to PHP page , php processes correctly and I use json_encode($response) to return. But instead of a simple true or false I get the source code for the page and it is causing a "parsererror" of course.
ajax call as follows
$.ajax({
type: "post",
url: "myprocessor.php",
dataType: 'json',
data: { "id" : idnumber, "action": "makeLive", "isLive" : "1" },
beforeSend: function(data) {
$("#ajaxInProgress").addClass('progress');
},
success: function(data) {
$("#status").removeClass().addClass((data.error === true) ? 'error' : 'success').text('Success! Appraiser is NO LONGER Live ').slideDown('slow');
},
error: function(data) {
$("#status").removeClass().addClass('error').text(' - Changing the Live status for this appraiser to "Not Live" has failed - APPRAISER IS STILL LIVE IN SYSTEM, please try again').slideDown('slow');
},
complete: function(data) {
$("#ajaxInProgress").removeClass('progress');
setTimeout(function() {
$("#status").slideUp('slow').removeClass();
},2000);
}
});
The php I post to is as follows:
if (isset($_POST['action'])) {
if($_POST['action']=='makeLive') {
$checkappraiser=mysql_query("SELECT * FROM table WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_numrows($checkappraiser)>0) {
$livesetting=mysql_result($checkappraiser,0,"live");
$livesetting=!$livesetting;
$runSql = mysql_query("UPDATE table SET live='$livesetting' WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if(!$runSql) {
$return['error'] = true;
} else {
$return['error'] = false;
}
}
}
echo json_encode($return);
}
Any suggestions would be great.
I am getting the proper data passed
I am getting the correct data updated in DB
My response is coming back as a parser error because it is trying to parse the source code as a json array.
Just a quick check, do you put <?php at the beginning of your php file?
That, or you're doing something wrong in your webserver, not passing files through to php correctly. Does hitting the php file directly load the source or the result?
If you hit page.php, does it load the same thing as if you hit page.phP or pHP, etc? It matters to web server filters, depending on the web server...
If you use tomcat for java, for example... you can turn off case sensitivity for finding files, but it does not turn off case sensitivity for mapping files to filters or servlets, so .jsp would load the jsp servlet, but .jsP would not.

Categories