two php script using ajax is no session - php

In a.php, i start the session, and i use ajax to post data to b.php.
in b.php, if have session, is find, if no session, do nothing.
but i always to read the session is NULL, i need to check user validity or security reason.
How to solve it?
the return always NULL
a.php
<?php
session_start();
$_SESSION['userid'] = '1123';
$_SESSION['username'] = 'henry';
if($_SESSION['userid']) {
?>
<script>
$("button#Search").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "b.php",
data: {
search: $("input#search").val()
},
success: function(response){
$("#message").html(response);
},
error: function(){
console.log("error");
return e.defaultPrevented || e.returnValue == false;
}
});
});
</script>
<?php } ?>
b.php
<?php
if($_SESSION['userid']) {
echo "success";
} else {
var_dump($_SESSION);
}
?>

You also need to add start session in b.php
session_start();
if($_SESSION['userid']) {
echo "success";
} else {
var_dump($_SESSION);
}

Your b.php file needs to have session_start() as well.
<?php
session_start();
if($_SESSION['userid']) {
echo "success";
} else {
var_dump($_SESSION);
}
?>

Related

if statement not working jquery

This should be simple, but doesn't work
Essentially I want to get a return result and reload my page if the answer is 'yes'
Here is the
timer.php
<?php
$filename = 'timer.tmr';
if (file_exists($filename)) {
unlink($filename);
echo 'yes';
} else {
echo 'no';
}
?>
and here is the script in my main file
var myVar = setInterval(function () {myTimer()}, 5000);
function myTimer() {
sendto = "timer.php";
$.get(sendto, function(data, status) {
if (data === 'yes') {
location.reload();
}
});
}
Basically in the timer.php
If the file exists I delete it and return a 'yes'
But the jquery doesn't do the reload function, if I check the data with an alert(data), it returns a 'yes' So I just don't understand the problem.
If you are getting into the if condition, then you should try window.location.href = window.location.href; instead of location.reload();
and If you're not getting into the if condition, change condition with if ($.trim(data) === "yes")
thanks to Shaunak Shukla (again thank you)
here is the final solution
var myVar = setInterval(function () {myTimer()}, 10000);
function myTimer() {
sendto = "timer.php";
$.get(sendto, function(data, status) {
if ($.trim(data) === "yes"){
location.reload();
}
});
}
it needed the trim(data) must have had something in it..
Use json_encode in the echos and improve your checking:
<?php
$filename = 'timer.tmr';
if (file_exists($filename)) {
unlink($filename);
if (!file_exists($filename))
echo json_encode('yes');
else
echo json_encode('no');
} else {
echo json_encode('no');
}
?>
And change the reload to a more direct scope:
var myVar = setInterval(function () {myTimer()}, 5000);
function myTimer() {
sendto = "timer.php";
$.get(sendto, function(data, status) {
if (data === 'yes'){
window.location.reload();
}
});
}
Let complete ajax request then try to reload :
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
I would Suggest, please check the Type casting (data type). I find, you have used === , it will check string to string or int to int.

Cannot get session value

In the header ( header.phtml ) I start the session :
<?php
if (session_status() == PHP_SESSION_NONE)
session_start();
?>
<!DOCTYPE html>
<html>
<head>
...
Now in other page I want to set a session value :
<script type="text/javascript">
$(document).ready(function() {
$("#add_reservS").on("click", function(e) {
<?php
$_SESSION['nb_ajout_client'] = 0;
?>
});
...
Then I increment this session value in other page :
public function ajouterExecAction($src = '', $pk_src = ''){
$client = new Client();
$client->ajouter($_POST);
if ($src == '')
$this->response->redirect('ReferentielClient');
else {
$_SESSION['nb_ajout_client']++;
...
}
...
}
Now inside another page I want to get this session value :
<script type="text/javascript">
$(document).ready(function() {
$("#btn_retour").on("click", function() {
var back = "<?php echo $previous; ?>";
if (back == "list_reserv")
window.history.back();
else {
var nb_back = "<?php echo $_SESSION['nb_ajout_client']; ?>";
alert("session nb ajout client = "+nb_back); // nb_back is blank !
}
});
});
</script>
The alert show a blank value ! So what is wrong in my approach ?
You must start each document with session_start();. While it is no longer required to be the very first line, it does need to be present before you do anything with a session in the file.
It is common to start the session from a common include file which is then included in every page which needs the session. Thus you only need to write it once.

Passing a PHP variable using ajax

I'm trying to pass a php variable from page1.html (which contains a php variable that I got from another form) to page2.php using ajax but it's not working, so I need your help.
code from page1.php:
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : <?php echo $admin; ?>,
gname : <?php echo $gname; ?>,
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>
The datas filename and content are being sent successfully but admin and gname are not.
Thanks in advance.
UPDATE:
<?php
if(isset($_GET['admin'])) {
$admin = $_GET['admin'];
}
if(isset($_GET['gname'])) {
$gname = $_GET['gname'];
}
?>
This code is where I get the php variable that I want to send, from another form which is irrelevant to this question.
Here you go buddy, replace your script code with this.
<script>
var url = 'page2.php';
var admin = '<?php echo $admin; ?>';
var gname = '<?php echo $gname; ?>';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : admin,
gname : gname,
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>
Youre using the type post so must use the $_POST in php
PHP
<?php
if(isset($_POST['admin'])) {
$admin = $_POST['admin'];
}
if(isset($_POST['gname'])) {
$gname = $_POST['gname'];
}
?>
You are using $_GET['admin'] which is used to fetch parameters delivered with GET method. You should be using $_POST['admin'] since you have set POST as your http request type in the JS code.
As everyone is saying you're mixing POST and GET. But it caught another thing that may bother you. Are those variables strings? If they are, maybe you're missing the apostrophe/single quote.
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : '<?php echo $admin; ?>',
gname : '<?php echo $gname; ?>',
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>>
Your below code
<?php
if(isset($_GET['admin'])) {
$admin = $_GET['admin'];
}
if(isset($_GET['gname'])) {
$gname = $_GET['gname'];
}
?>
is to be replaced by
<?php
if(isset($_POST['admin'])) {
$admin = $_POST['admin'];
}
if(isset($_POST['gname'])) {
$gname = $_POST['gname'];
}
?>
You are sending POST parameters,while using get in PHP script. And another issue is you are not using quotes with $admin and $gname variables in ajax request.
Try following :
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : '<?php echo $admin; ?>',
gname : '<?php echo $gname; ?>',
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>
PHP Script:
<?php
if(isset($_POST['admin'])) {
$admin = $_POST['admin'];
}
if(isset($_POST['gname'])) {
$gname = $_POST['gname'];
}
?>
Check if it helps you.

jquery post on document ready

All i want is, a data will pass into this php file: check.php and this php file will pass data into that function when the page is ready. this is just an expirement.
ok I have this code:
$(document).ready(function() {
$.post("check.php", {
name: "log"
}, function(data) {
if (data === "yes") {
alert('has been login');
} else {
alert('has not login');
}
});
});​
and i have this php code ("check.php") where the jquery post will pass the data into.
​
<? //check
$chk = $_POST['name'];
if (isset($chk === "log")) {
if (isset($_COOKIE['admin'])) {
if ($_COOKIE['admin'] === "login") {
echo "yes";
}
} else {
echo "no";
}
} else {
echo "no";
}
?>
but nothing happen, even i change the whole code in check.php into: "echo "yes";" theres nothing happen, i guess, its either there is no data receive or there is no data pass. Hope someone could help me into this simple and cute problem that im stuck with. thank you in advance
I think you missed a closing brace. This just works as expected:
$.post('check.php', { name: 'log' }, function(data) {
if (data === "yes")
{
alert ('has been login');
}
else
{
alert ('has not login');
}
});
Run this JSFiddle http://jsfiddle.net/S53k5/
and you will see the call passing by in Fiddler.
I would guess it's because you're using the header "name" and that is a reserved keyword.

Call to a php logout script using jQuery

I want my user to be automatically loged out of the site if there has been no activity for half hour. (Code You see below is set for 70 seconds not 1/2 hour).
I realize that what I need is to use jQuery ... this I am extremly new to ... to load my php script. (I've been working on this for way too long) This is what I have so far.
This is in the head of my page.
var log_me_out = true;
setTimeout(function(){
$.post({
url: "check_time.php",
//data: optional, the data you send with your php-script
success:function(){
if(log_me_out == 'yes'){
window.location = 'index_test.php';
}
}
})
}, 80000);
</script>
This my check_time.php page
<script type="text/javascript">
var log_me_out = true;
</script>
<?php
include('pagetoretrivepassword.inc.php');
session_start();
if($_SESSION['admin_login'] != $password){
session_unset();
session_destroy();
?>
<script type="text/javascript">
log_me_out = 'yes';
</script>
<?php
}else{
?>
<script type="text/javascript">
log_me_out = 'no';
</script>
<?php
}
?>
Well it looks good to me, but I would suggest a bit of a simplification. The best way to do it would be to use the code you have within the setTimeout function, and within it check when the user was last active. So set up a variable like 'lastActive', and using something like:
$(document).click(function(){
var currentTime = new Date();
lastActive = currentTime.getSeconds();
});
Then in your setTimeout function you do something like:
var currentTime = new Date();
if(lastActive + 5000 < currentTime.getSeconds()){
//If user hasn't been active for 5 seconds...
//AJAX call to PHP script
}else {
setTimeout(theSameFunction(),5000);
}
Then in your PHP simply destroy the session, and the success callback function should then simply have:
window.location = 'index_test.php';
To send users on their way.
The javascript you wrote on your php file will not be executed.
To know what your php script do, use that code :
Javascript :
$.post('check_time.php', function(data)
{
if(data == 'yes')
{
window.location = 'index_test.php';
}
});
Php :
session_start();
if($_SESSION['admin_login'] != $password)
{
session_unset();
session_destroy();
echo 'yes';
}
else
{
echo 'no';
}
Your code needs to return something that is parsable such as JSON, XML, or HTML. For example, change your check_time.php to output this:
<?php
include('pagetoretrivepassword.inc.php');
session_start();
header('Content-type: application/json');
if($_SESSION['admin_login'] != $password){
session_unset();
session_destroy();
json_encode(array("log_me_out"=>"true");
}else{
json_encode(array("log_me_out"=>"false");
}
?>
Edit your HTML to include this line of JQuery code:
setTimeout(function(){
$.post("check_time.php", function(d){
if(d.log_me_out){
window.location = 'index_test.php';
}
});
}, 80000);
This problem is solved here is the final working code
code on home page:
ini_set('session.gc_maxlifetime',1800);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
session_start();
if($_SESSION['admin_login'] != $password){
header('Location: index.php');
exit();
}
if(isset($_SESSION['last_activity']) && (time()-$_SESSION['last_activity'] >1800)){
// last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
header('Location: index.php');
exit();
}
$_SESSION['last_activity'] = time(); // update last activity time stamp
?>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function timedCount(){
$.ajax({
type: 'POST',
url: "check_time.php",
success: function(data){
if (jQuery.trim(data) == "LOGOUT") {
window.location = 'LOGOUT.php';
}
}
});
setTimeout("timedCount()",10000);
};
</script>
Here is the code on the check_time.php page
<?php
session_start();
if (isset($_SESSION['last_activity'])){
if(time() - $_SESSION['last_activity'] > 1800){
session_unset();
session_destroy();
echo "LOGOUT";
}
}else{
echo "LOGOUT";
}
?>

Categories