Cannot get session value - php

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.

Related

How do I get response data from php with ajax (one file)?

I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.
The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.
Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.
Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.

Open modal window after submitted and returned to page

I have function validate my form and after form submitted
else
{
$('.submit-button').val('Wait please...');
$('.submit-button').attr('disabled', 'disabled');
return true;
}
PHP redirect to main page
function wpcallback_get_target() {
global $wpcallback_plugin_option;
if($value = $callback_plugin_option['target'])
return get_permalink($value);
return get_site_url();
}
PHP get site url then how I can make thanks modal window opened?
I tried with .modal but can't find right place for it.
$('#myModal').modal('show');
place $('#myModal').modal('show'); in the bottom of you view file or you can add following code in head tag
$(document).ready(function(){
$('#myModal').modal('show');
});
to prevent model every time on page load, update your PHP file:
function wpcallback_get_target() {
global $wpcallback_plugin_option;
if($value = $callback_plugin_option['target'])
return get_permalink($value);
$url = get_site_url();
return $url."?response=true";
}
in view file:
<?php if(isset($_GET['response']) && $_GET['response'] == 'true'){ ?>
$(document).ready(function(){
$('#myModal').modal('show');
});
<?php } ?>
use Javascript code:
$(document).ready(function(){
var myURL = window.location;
var res = myURL.search("response=true");
if(res > 0){
$('#myModal').modal('show');
}
});
Try this on your php.
echo "<script>
$(window).load(function(){
$('#yourthanksmodel').modal('show');
});
</script>";

php maintain session between page having class and another page without class

Page1.php (Not Full code)
<?php
class A {
function Session() {
session_start(); // assume session started here
}
?>
<button onclick="play('MyVideo.mp4',event)">MyVideo1</button
<script type="text/javascript">
function play(video,e) {
var videoFile = 'folder1/product.php?v=' + video;
$('#divVideo video source').attr('src', videoFile);
$("#divVideo video")[0].load();
}
</script>
<?php
}
?>
product.php (this page is not a class)
In product.php I am having some code, but if(isset($_SESSION)){ condition failed ,so got to understand that session getting failed.
How do I make session pass in product.php? I cannot use $this in this product.php page.
To pass data to your products.php file you would need to use ajax, then you can pass the variable from the session via ajax to your file.
At first we need to capture the session variable in hidden input
<input type="hidden" value="<?php $_SESSION['variable_name']?>" class="sessionName" >
now the js file
<script>
$(document).ready(function() {
var name = $('.sessionName').val();
$.ajax({
url : 'products.php', // url to your file could be different
type : 'post',
data : {
sessName: name )
},
success : function(data) {
console.log(data);// check console long for output and errors
}
});
});
</script>
in your products.php file
if (isset($_POST['sessName']) ){
$session_name = $_POST['sessName']
//output to console.log in case the variable is set
echo 'Session Variable : '.$session_name;
}else{
//output to console.log when variable is not set
echo 'Session Variable is not Set'; // if not
}
Hope this help.

reading facebook token in url, storing in cookie, echoing in file

I have a multi -part process
step 1:on page.php I evoke a facebook pop-up authentication window with the URI going to page2.php
https://facebook.com/dialog/oauth?client_id=ID&redirect_uri=http://domain.com/page2.php?-Your+Special+Token+1170-&type=user_agent&fbconnect=1&scope=publish_stream
on page2.php I want to process this token by reading it from the url and storing it as a cookie
<?php
session_start();
if ( empty($tkn) ) { ?>
<script>
(function () {
try {
var q = location.href.split('#');
var a = q[1];
var q2 = a.split('=');
var a2 = q2[1];
var q3 = a2.split('&');
var a3 = q3[0];
setTimeout(function () {
top.location.replace('http://domain.com/cookie.php?tkn=' + a3);
}, 200);
} catch (e) {
top.location.replace('http://domain.com/cookie.php?retry=1&tk=broken_' + encodeURI(e.message));
}
})()
</script><? } else {
print $_GET['tkn'];
}
$_SESSION['tkn'] = $tkn;
$tkn = $_POST["tkn"];
if(isset($tkn)) {
setcookie("tkn", $tkn);
echo "success";
}
?>
page.php detects the cookie and echoes out the token $tkn and reloads the page
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$.post('page2.php',{tkn: tkn}, function(data){
if(data=='success'){
location.reload(true)
}
});
</script>
<?php echo $tkn; ?>
the problem is I cant get any of this to work. The popup goes into an infinite error loop and nothing is refreshed or echoed.

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