Do Ajax Requests Retain PHP Session Info

Do AJAX requests retain PHP Session info?

The answer is yes:

Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way.

From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.

How to store session at remote server with ajax request javascript/PHP

It is not possible to keep the session through ajax call because it creates a new http request every time.

SOLUTION is store seesion id at client side and send the id everytime with request to remote server. At remote server generate new session with the old id.
https://404it.no/en/blog/javascript_cross-domain_request_with_session

PHP session variables not preserved with ajax

I think you're missing session_start() on the page that Ajax calls.

You need:

<?php
session_start();
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>

Maintaining $_SESSION data while making ajax requests through jquery in PHP?

First:
You are not sending the "token"-variable with your Ajax call. You are sending the variable dataString which does not include the token variable. You have commented the token part out...

var token="<?php echo $_GET['token'];?>"; 
var dataString = 'videoId='+ fields[0]; // + '&token=' + token;

Second:
You can only send Ajax with POST or GET

in your ajax call you are using GET, so you should check for $_GET; Not $_SESSION.

Refresh PHP SESSION var after AJAX request

Finally I solved this, the solution, JSON. Is not necessary to refresh PHP SESSION vars on index.php, only on callSession04.php, simply I've to use AJAX callback to reflect the current server state parsing JSON array on index.php from callSession04.php then you can set new current page and rows per page vars.

index.php

<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p><a href="destroy.php">Reset</a></p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
$rows=10;
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
$rows=<? echo $_SESSION['rows']; ?>;
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
var json = $.parseJSON(data);
$("#content").html(json.html);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
var json = $.parseJSON(data);
$rows=json.rows;
$("#content").html(json.html);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp="+$actp+"&rows="+$rows,
success: function(data) {
var json = $.parseJSON(data);
$actp=json.actp;
$("#content").html(json.html);
}
});
});
</script>
</body>
</html>

callSession04.php

<? session_start();

$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}

$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];

if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}

if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}

$_SESSION['rows']=$rows;
$_SESSION['actp']=$actp;

$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;

if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}

$html = "<p align='center'><strong>EMPLEADOS</strong></p>";
$html .= "<table border='1' cellspacing='0' cellpadding='5'>";
$html .= "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
$html .= "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>";
$html .= "<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
$html .= "</table>";
$aPag = array("rows"=>$rows,"actp"=>$actp,"html"=>$html);
echo json_encode($aPag);
?>

Session information not maintained while AJAX requests

The session data are stored usually in cookies for all browsers, or you can use the query string of your request to pass parameters. eg: .../render_latest.php?lastepoch=123456 and read the lastepoch parameter in your php.

Or you can use HTML5 client-side storage in modern browsers.

Avoid session timeout reset when sending ajax request

If (and only IF) your Ajax call is completely session-agnostic (that is, it doesn't required to be logged in to run, it doesn't need any session data from the user, etc) you could serve the Ajax request from a separate ajax-specific controller and then inhibit the session library autoload when that specific controller is used.

If the ajax call requires a logged in user you're mostly out of luck.

However, if you meet these conditions, find the $autoload['libraries] section in application/config/autoload.php and use this dirty hack:

// Here, an array with the libraries you want/need to be loaded on every controller
$autoload['libraries'] = array('form_validation');

// Dirty hack to avoid loading the session library on controllers that don't use session data and don't require the user to have an active session
$CI =& get_instance();
// uncomment the one that fits you better
// Alternative 1: you only have a single controller that doesn't need the session library
// if ($CI->router->fetch_class() != 'dmz') array_push($autoload['libraries'], 'session');
// END alternative 1

// Alternative 2: you have more than one controller that doesn't need the session library
// if (array_search($CI->router->fetch_class(), array('dmz', 'moredmz')) === false) array_push($autoload['libraries'], 'session');
// END alternative 2

In the above code, dmz and moredmz are my two imaginary controller names that require the session library to not be loaded. Whenever these are NOT used, the session library is pushed into autoload and thus loaded. Otherwise, the session library is ignored.

I actually have this running on one of my sites in order to allow the health checks from my loadbalancer to run (once every 5 seconds on each application server, from both the primary loadbalancer and its backup) and fill up my sessions table with useless data and works like a charm.

Not sure what version of CI you're using, but the above code is tested on CI 3.1.11.

Now, as you state the Ajax call requires the session driver, the only way around this would be to mess a little with the Session driver itself. In 3.1.11, the session driver is located in system/libraries/Session/Session.php and the part you'd need to change is the final part of the constructor method (look from line 160 onwards). For this example, I'll assume your Ajax calls are handled by a specific controller called "Ajax"

// This is from line 160 onwards
elseif (isset($_COOKIE[$this->_config['cookie_name']]) && $_COOKIE[$this->_config['cookie_name']] === session_id())
{
$CI =& get_instance();
$new_validity = ($CI->router->fetch_class() !== 'ajax') ? time() + $this->_config['cookie_lifetime'] : $_SESSION['__ci_last_regenerate'] + $this->_config['cookie_lifetime'];

setcookie(
$this->_config['cookie_name'],
session_id(),
(empty($this->_config['cookie_lifetime']) ? 0 : $new_validity),
$this->_config['cookie_path'],
$this->_config['cookie_domain'],
$this->_config['cookie_secure'],
TRUE
);
}

$this->_ci_init_vars();

log_message('info', "Session: Class initialized using '".$this->_driver."' driver.");

In a nutshell, this example (haven't tested it so please do before deploying it, it may have a typo or two) will first instantiate the CI core and get the controller name from the Router. If it's a regular controller, it'll determine the new cookie validity as "now plus the cookie validity from the config". If it's the ajax controller, the cookie validity will be the same as the current validity (last regeneration time plus cookie validity.. had to reiterate it as the ternary operator requires it)

Afterwards, the setcookie is modified to use the pre-computed cookie validity depending on what the _config['cookie_lifetime'] value is.

Session do not work on ajaxRequest [How to count ajax-request with session variable]

After testing your pages, your problem is related to your domain.

http://www.huntinggrounds.de/aa.html is working fine, not http://huntinggrounds.de/aa.html

For security reasons, cookie is per-domain specific. Cookie set by PHP on http://huntinggrounds.de/aa.html will not work on http://www.huntinggrounds.de/aa.html depending of your configuration.

To by pass this problem, don't set full URL in your ajax. Preferer relative URI.

$.get( "/collect?"+setParameter(defs),
function( data ) {
try {
console.log("New count is : ",data);
} catch(e) {
// if there is no response
console.log( "No answer : ", data);
}
})


Related Topics



Leave a reply



Submit