PHP Session loses value after SECOND redirect - javascript

After combing through SO and trying the approved suggestions found here, my related problem persists. My page starts with a simple login and then you navigate to other potential pages through drop down menus. When I redirect from the index page to a welcome page, I can recall values from my $_SESSION array on to the welcome page. The problem is when you navigate to another page after after that point. The content of the $_SESSION array gets erased. Even if I reload the same page that already has a return from the $_SESSION array, the array gets erased.
I use XAMPP OSX, php 7.9.2 and localhost on my own computer. I've restarted XAMPP. I've emptied cache and restarted my browser. I've tried other browsers. I've rebooted my computer.
Is there something I can do with my server settings? What could be the source of my problem?
What is very strange is that the issue came out of the blue. I was able to preserve $_SESSION with no problems weeks before and all of a sudden it began to drop its values.
Update 1
So I've made some changes to my code below to have a separate AJAX page and php pages to really clarify what I'm doing. The problem seems to have improved with what I did. HOWEVER, there still remains some mysteries:
1) On log out, I get a warning from my AJAX output that the SESSION variable doesn't exist. This is strange as I am able to print out my session content from my php pages when I've logged in and I navigate to other pages.
2) I am unable to make a simple function call (an alert popup) when my footer loads for every page. This alert popup is on the same page as AJAX functions (which seem to work), but the popup doesn't pop.
Header
<?php session_start() ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>test site</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet "href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class="container col-xs-12" id="OPheader">
<div id="logoText">
<p>
Test Pages
</p>
</div>
Navigation Menus
<div class="btn-group menuButton ">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
So what you wanna do? <span class="caret"></span>
</button>
<ul class="dropdown-menu" id="daMenu">
<li>Continue procrastination</li>
</ul>
</div>
<!-- ============ user personal menu ====== -->
<div class="btn-group userMenuButton ">
<button type="button" class="btn btn-default dropdown-toggle" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<label id="user-name-icon" >Your name</label>
<!-- Insert user name from database here -->
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="daUserMenu">
<li>Order another pizza</li>
<li role="separator" class="divider"></li>
<li><a onclick="javascript: killSession();" >Log Out</a></li>
</ul>
</div>
Index page
<?php include("testHeader.php"); ?>
<?php include("testIndexTools.php"); ?>
</div>
</div>
<!--
====================== Login Fields ======================================
-->
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="well" id="loginBox">
<div>
<div id="loginErrorMsg" ></div>
<form method="POST" action="">
<div class="enterBox">User: <input type="text" name="user_name" placeholder="uh... who?" >
</div>
<br>
<div class="enterBox">Password: <input type="text" name="user_pw" placeholder="Don't mess this up" >
</div>
<br>
<div >
<input class="btn btn-primary submitText" type="submit" name="login_submit" value="Submit your soul">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var error = "Login unsuccessful. Please re-enter credentials.";
var disp = document.getElementById('loginErrorMsg');
function showError(){
disp.innerHTML = error;
}
</script>
<?php include("testFooter.php"); ?>
</body>
</html>
PHP Tools for Index page
<?php
$errors = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
list($errors) = validate_form(); // check for blank input fields
if ($errors) { // If validate_form() returns errors,
show_errors($errors); // show error messages
} else {
process_form();
}
}
// on succesful login, this function is called to redirect page
function process_form(){
session_start();
$_SESSION['logged_user'] = htmlentities($_POST['user_name']);
if (isset($_SESSION['logged_user'])){
session_regenerate_id(true);
header("Location: /OPsite/SOmock/testHomePage.php");
exit();
} else {
echo "Session wasn't set so not redirecrting";
exit();
}
}
function show_errors($errors){
echo '<script type="text/javascript"> showError(); </script>';
}
// validate your data
function validate_form(){
$errors = array();
$userCu = trim($_POST['user_name'] ?? '');
$userPw = trim($_POST['user_pw'] ?? '');
if (strlen($userCu) == 0){
$errors[] = "Please enter name";
return $errors;
} else if (strlen($userPw) == 0) {
$errors[] = "Please enter password";
return $errors;
}
}
?>
Welcome page
<?php include("testHeader.php"); ?>
<?php include("testMenu-bar.php"); ?>
<?php include("testWelcomePageTools.php"); ?>
</div>
</div>
<!-- ================================= welcome Page =============== -->
<div class="row" id="homePage">
<div class="container ">
<h1> Stop procrastinating and get back to work</h1><br>
</div>
</div>
<?php include("testFooter.php") ?>
</body>
</html>
PHP tools for Welcome Page
<?php
// AJAX call to set name from HomePage
if (isset($_POST['sessName'])){
// $_SESSION['logged_user'] = htmlentities($_POST['user_name']); // user-icon name set here
$userName = $_SESSION['logged_user'];
// echo $_SESSION['logged_user'];
echo "Session data exists<br>";
echo $userName;
// print_r($_SESSION); // when homePage loads, this is to check array
// echo "sessName";
} else {
$noSession = "No session data<br>";
echo $noSession;
print_r($_SESSION);
}
?>
other page to navigate to
<?php include("testHeader.php"); ?>
<?php include("testMenu-bar.php"); ?>
<?php
echo "this is the testSession Page<br>";
print_r($_SESSION);
?>
<?php include("testFooter.php") ?>
</body>
</html>
Footer
<script type="text/javascript" src="testFooterJS.js">baba();</script>
<!-- === log out behavoiur ============== -->
<?php
// AJAX call to kill session
if (isset($_POST['killSess'])){
unset($_SESSION['logged_user']);
session_destroy();
$_SESSION = array();
exit();
}
?>
javascript/AJAX page for logging in/out
//====== AJAX log in behaviour ==========
function sessionName(){
alert("name calling");
$.ajax({
type: 'post',
url: 'testHomePageTools.php',
data:'sessName', // in PHP page, this will correspond with: $_POST['action'] == 'fillMenu'
dataType: 'text',
success: function (data) {
alert("Your name" +data);
var userName = data;
var icon = document.getElementById('user-name-icon');
icon.innerHTML = "You are logged in as: " + userName;
alert("You are logged in as: " + userName);
},
error: function(data){
alert("something's gone wrong on entry");
console.log(data);
// alert(data);
}
});
};
//====== AJAX log out behaviour ==========
function killSession(){
$.ajax({
type: 'post',
url: 'testFooter.php',
data:'killSess', // in PHP page, this will correspond with: $_POST['action'] == 'fillMenu'
dataType: 'text',
success: function (data) {
console.log(data);
alert("Bye bye");
window.location = "http://localhost/OPsite/SOmock/testIndex.php";
},
error: function(data){
alert("something's gone wrong on exit");
console.log(data);
// alert(data);
}
});
};
// ============= test to see if footer loads ===========
function baba(){
alert("footer loaded");
};

I figured out my problem. After my code updated as posted, I discovered that my problem was that I thought that having session_start() on my header would address and cover all the pages that included the header. This is not the case. The session_start() has to be on literally every php page that refers to $_SESSION super global. This was not very clear on my research, but through trial and error I figured it out.
Thanks

Related

Can't return html from controller using Ajax calls in a Chat app

So i'm building an integrated chat app in CRM. Whenever the logged in user click on a contact it displays the chat history between both users using Ajax calls, and this is where troubles begin.
So here's my Ajax Call code:
function GetChatHistory(receiver_id){
$.ajax({
dataType : "json",
url: '/chat/get_chat_history_by_user',
data:{receiver_id:receiver_id},
success:function(data)
{
$('#chathistory').html(data);
ScrollDown();
},
error: function (jqXHR, status, err) {
// alert('Local error callback');
alert("error fetching")
}
});
}
this is my controller
public function get_chat_history_by_user(){
//get the receiver id
$receiver_id = $this->input->get('receiver_id');
//get the sender id
$Logged_sender_id = $this->session->userdata['user_id'];
$history = $this->chat_model->GetReciverChatHistory($receiver_id);
foreach($history as $chat):
$message_id = $chat['id'];
$sender_id = $chat['sender_id'];
$userName = $this->UserModel->GetName($chat['sender_id']);
$userPic = $this->UserModel->PictureUrlById($chat['sender_id']);
$messagebody = $chat['message'];
$messagedatetime = date('d M H:i A',strtotime($chat['message_date_time']));
?>
<?php if($Logged_sender_id!=$sender_id){?>
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->
<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }else{?>
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->
<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }?>
<?php
endforeach;
}
the simple version of the view and the div i want to insert data in it :
<div id="chathistory"></div>
Please note that the models are written correctly(i did test them), and the call is written correctly because whenever i remove the foreach loop and add this to my controller :
echo json_encode($history);
and then console log the data in my ajax call i get the full chat history without a problem. so my guess is that there's something wrong with foreach loop and the html rendering !
ALSO : i did review some simple web app chat on github and they did write the controller with the same manner and it work perfectly fine for them. So what do you think is the problem please?
dataType : "json"
tells jQuery to expect JSON in the response, but you are returning HTML from the controller. So it will likely throw an error when it tries to parse your HTML as JSON. Either remove that line, or specify
dataType: "html"
instead

Receiving data from HTTP GET Request before redirecting to another page through a hyperlink

I would like to receive data from HTTP GET request and store it in a PHP variable before redirecting to another page. Here is the code.
<?php
session_start();
require("dbconfig.php");
?>
</html>
<head>
<a href="https://www.google.com/" class="btn btn-success" id="link" type="button" >Click me</a>
<script type="text/javascript">
jscounter=1;
jscounter++;
document.getElementById("link").onclick = function () {
alert("javascript counter variable is " +jscounter);
window.location = "?js_var=" + jscounter;
}
</script>
</head>
<body>
</body>
<?php
if (isset($_GET['js_var'])) {
$counter = $_GET['js_var'];
echo "PHP counter variable is ".$counter;
$squery = "update mycounter set counter=$counter";
if(mysqli_query($dbc, $squery)) {
echo "Counter added to db successfully to DB";
}
else {
echo mysqli_error($dbc);
}
}
?>
</html>
The above code works when no link is mentioned in the hyperlink i.e., as below.
<a href="#" class="btn btn-success" id="link" type="button" >Click me</a>
Any help will be much appreciated.
You can leave your <a href> code as it is. When you're done getting your data and saving it.
Just redirect to desired page as :
header('Location: http://your.desired.link/');

How can I launch Google Sheets Script Code into a Google app script web app?

I have a Google Sheet Code which has a UI part ie html and code.gs
the problem is inside Google sheet I am getting a webpage and the authentication and other functions are working well but if I add the doGet() in code.gs and convert that to webapp the functions are not working and the scriptlets are displaying in the html page also the functions broke .
Since the code inside the html page is running in server side of the google app script sheet but it fails to run in client side as the reference are not directing to the server side code.gs
I need to make it work with the client side code , it should functional just like it work inside the Google spreadsheet
I am using Google Apps Scripts Oauth
and getting a facebook token this is the Original work which successfully generate a token and access to facebook data Original Work
These are the codes
<div class="tab-content">
<!-- Home -->
<div id="ads" class="tab-pane fade in active">
<div id="page-content-wrapper">
<div class="hamburger is-closed" data-toggle="offcanvas">
<span class="hamb-top"></span>
<span class="hamb-middle"></span>
<span class="hamb-bottom"></span>
</div>
<div class="container">
<? if(!getService().hasAccess()) { ?>
<div class="row">
<div class="col-md-12 col-lg-12">
<p style="font-size:25px;">Features:</p>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12" align='center'>
<a class="loginBtn loginBtn--facebook btn btn-info" href='<?=getService().getAuthorizationUrl()?>' target='_blank'>Authorize Facebook</a>
</div>
</div>
<? } else { ?>
<p style='color:green'>Authorization Success</p>
<div class="form-group">
<label for="accountData">Select Account:</label><span class="glyphicon glyphicon-question-sign help" title="Select Account To Export"></span>
<select id="accountData" style="width: 100%">
<? if (getService().hasAccess()) { ?>
<? var data = adAccounts() ?>
<? if (data != false) { ?>
<? data = data['facebookAccountData'] ?>
<optgroup label="Ad Accounts">
<? for (i=0; i<data.length; i++) { ?>
<option value="<?= data[i]['account_id'] ?>" data-type="facebookAds"><?= data[i]['name'] ?> (<?= data[i]['account_id'] ?>)</option>
<? } ?>
</optgroup>
<? } ?>
<? } ?>
</select>
</div>
the Login Button itself calling a function inside the code.gs but it is only work inside the google sheet but not in a web app or any html browser or client side
So how to refer this into the code.gs
href='<?=getService().getAuthorizationUrl()
This is the code.gs PART
function fbAuth(){
var UI=HtmlService.createTemplate("<b><a href='<?=getService().getAuthorizationUrl()?>' target='_blank'>Click To Authorize</a></b><br /><? if(getService().hasAccess())"+
"{ ?> <?!= <p><span style='color:green'>Authorized Successfully</span></p> } else {?> <?!= <p><span style='color:red'>Not Authorized</span></p> }").evaluate()
SpreadsheetApp.getUi().showModalDialog(UI, "Facebook Authorization")
}
function getService() {
return OAuth2.createService('Facebook')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://www.facebook.com/dialog/oauth')
.setTokenUrl('https://graph.facebook.com/v3.2/oauth/access_token')
// Set the client ID and secret.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function that should be invoked to complete
// the OAuth flow.
.setCallbackFunction('authCallback')
//Set Scope
.setScope('ads_read manage_pages publish_pages pages_show_list')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties());
}
function authCallback(request) {
var isAuthorized = getService().handleCallback(request);
if (isAuthorized) {
successUI(true)
showBar()
return HtmlService.createHtmlOutput('Success! You can close this tab.<script>window.top.close()</script>');
} else {
successUI(false)
showBar()
return HtmlService.createHtmlOutput('Denied. You can close this tab.<script>window.top.close()</script>');
}
}
function reset() {
var service = getService();
service.reset();
showBar()
SpreadsheetApp.getUi().alert("Token Reset Success!!")
}
function successUI(isAuth){
if(isAuth){
var UI=HtmlService.createTemplate("<b><span style='color:green'>Authorization Successful</span></b>").evaluate()
SpreadsheetApp.getUi().showModalDialog(UI, "Authorization Status") } else
{var UI=HtmlService.createTemplate("<b><span style='color:red'>Authorization Fail</span></b>").evaluate()
SpreadsheetApp.getUi().showModalDialog(UI, "Authorization Status")}
}
Finally found the resolution , Need to add html tags and body tags in the html file
and in gs file we should add the
function doGet(){
return HtmlService.createTemplateFromFile('html').evaluate()
}
than it should return a html page without brackets

Ajax Tabs for Wordpress that loads and runs different shortcodes when user changes the tab

How does one execute a shortcode, which is placed in a tab, only when the user clicks on the Tab's Title. How do we do this for five tabs? MY objective is to reduce load time of me website. So, only that content which the user wants must load when he clicks on the tab.
I'm fairly certain the best way to do this is by utilizing Wordpress's admin-ajax.php. I've searched a great deal. And I've found most of the code (I think) to create the AJAX tabs. But, when I fire the code it doesn't show up. Rather the HTML shows us, the AJAX doesn't.
$(document).ready(function() {
$('.my_tabs a').click(function(e) {
e.preventDefault();
var tab_id = $('this').attr('id');
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({
action: 'my_tab_menu',
id: tab_id
}),
success: function(data) {
$('#my_tab' + tab_id).html(data);
},
error: function(data) {
alert("Error!");
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_tabs">
Tab 1
Tab 2
Tab 3
Tab 4
Tab 5
</div>
<div class="my_section" id="my_tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my_section" id="my_tab2">
<?php echo do_shortcode ('[shortcode-2]'); ?>
</div>
<div class="my_section" id="my_tab3">
<?php echo do_shortcode ('[shortcode-3]'); ?>
</div>
<div class="my_section" id="my_tab4">
<?php echo do_shortcode ('[shortcode-4]'); ?>
</div>
<div class="my_section" id="my_tab5">
<?php echo do_shortcode ('[shortcode-5]'); ?>
</div>
I add all the code directly into the page using a page-builder. So, I'm not using functions.php to add_action for this particular tab that I'm trying to implement.
I found all the code from a similar post on stackover:
Ajax tabs (wordpress)
They call template_parts into the tabs. Where as I want to execute a shortcode.
I'm what you'd call a coding bimbo. All help shall be much appreciated.
Thank you. And if you've managed to read till here, you deserve to have a pleasant day. :D
Okay, so you can't achieve it the way you have laid your template. As soon as you echo the shortcode and the browser renders the page, the shortcode contents must have printed. You need to create a custom-page-template.php, create a page and on that page you need to send the shortcode handler as soon as you click on the tab through GET or POST method using ajax.
In your Custom Template you receive the [shortcode-1]. An example code would be like you see below:
<?php
/*
Template Name: Shortcode Processor
*/
$current_shortcode = $_POST['shortcode_name'];
?>
<div id="shortcode-contents">
<?php echo do_shortcode($current_shortcode); ?>
</div>
Now you have the response in your Ajax Call. You can now inject the success html inside your desired tab.
Try
<button class="tabs" id="my-tabid1" data-target=".my-section1.box">Tab 1</button>
<button class="tabs" id="my-tabid2" data-target=".my-section2.box">Tab 2</button>
<button class="tabs" id="my-tabid3" data-target=".my-section3.box">Tab 3</button>
<div class="my_section1 box active" id="my-tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section2 box" id="my-tab2">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section3 box" id="my_tab3">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<style>
.box {
display: none;
}
.box.active {
display: block;
}
</style>
<script>
$('.tabs').on('click', function(){
var $target = $($(this).data('target'));
$target.siblings().removeClass('active');
$target.addClass('active');
});
</script>

Updating span with jQuery, fetching it with PHP?

I have a jQuery-script that updates a span when the user clicks on different buttons. It updates and displays as desired.
But I want to fetch this "variable" with PHP and input it into a file.
When the document loads the value of the span is 0, and gets higher as the user click specific buttons. When I write the value of the span to my text file it is always 0. Help?
jQuery:
$(".button").click(function()
{
$(this).addClass("button-clicked");
$(this).siblings(".button").addClass("disabled");
$(this).siblings(".rett").addClass("rett-ved-feil");
$(this).unbind("click");
$(this).siblings(".button").unbind("click");
if($(this).hasClass("rett"))
{
rettVar++;
$("#antall-rett").html(rettVar);
$("#score").html(rettVar);
$(this).addClass("button-clicked-riktig");
}
});
PHP:
if (isset($_POST["submit"]))
{
$doc = new DOMDocument;
$doc->loadHTMLFile('index.php');
$node = $doc->getElementById('score');
$score = $node->nodeValue;
$fil = fopen("score.txt","a");
$loglinje = $_POST["navn"] . ": " . $score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
}
HTML:
<!doctype html>
<title>Huskampanje Quiz</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="mediaqueries.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="js/jquery-1.11.2.js" type="text/javascript"></script>
<script src="js/myjs.js" type="text/javascript"></script>
<script src="js/scrollToggle.js" type="text/javascript"></script>
<section class="section" id="intro">
<div class="content">
<h1>Huskampanje quiz<br /><span class="handsome">Ta quizen her</span></h1>
</div>
<img src="img/pil.png" id="pil" />
</section>
<section class="section" id="håndverker-section">
<div class="content">
<p>
Når det gis et prisoverslag på en håndverkertejeneste kan endelig pris maks overstige..
</p>
<span class="button">5%</span>
<span class="button">10%</span>
<span class="button rett">15%</span>
<span class="button">20%</span>
<span class="steps">4/10</span>
</div>
</section>
<section class="section" id="naturskade-section">
<div class="content">
<p>
Ved påsketider har snøen ligget en stund på hyttetak, og oppnår høyere egenvekt enn når den er fersk. Om vi har et
hyttetak på 100 kvadratmeter og snødybden er 1 meter vil vekten av snøen være omlag..
</p>
<span class="button rett">30 tonn</span>
<span class="button">10 tonn</span>
<span class="button">5 tonn</span>
<span class="button">20 tonn</span>
<span class="steps">10/10</span>
</div>
</section>
<ul id="sticky">
<li id="header-sticky">Antall rett</li>
<li id="antall-rett">0</li>
</ul>
<section id="resultat">
<div class="content" id="resultat-content">
<div class="score">
<span id="score">0</span>
<form action="index.php" method="post">
<input type="text" name="navn">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST["submit"]))
{
$doc = new DOMDocument;
$doc->loadHTMLFile('index.php');
$node = $doc->getElementById('score');
$score = $node->nodeValue;
$fil = fopen("score.txt","a");
$loglinje = $_POST["navn"] . ": " . $score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
}
?>
</div>
</div>
</section>
As they told you, Javascript is client side while PHP is server side.
This means that what in client side happends, stays there and server doesn't care at all. If you want to update your file with the value, you got two ways to do it.
1.AJAX, send the value async to a php file and write the value desired into your file/database...
2.Make a form and retrieve the data and save it where you want. For this, make hidden inputs for example that will increment with every click.
Edit: for number 2, if you have multiple pages, you can have an input hidden with name, for example: "right_answers"
<form>
...
<!-- first page -->
<input type="hidden" name="right_answers" value="0">
...
</form>
Then in the next page, at the start, check if the answer is correct:
<?php
if($_POST['question'] == "answer") {
$goodAnswer = $_POST['right_answers']+1;
}
else {
$goodAnswer = $_POST['right_answer'];
}
?>
<form>
...
<input type="hidden" name="right_answers" value="<?php echo $goodAnswers; ?>">
...
</form>
This way you will always know the correct answers the user made. It's just an idea, sure there are better ways.
Your PHP script (file) will run on your server. The user, who has opened your webpage somewhere in the world, can't and never should see or alter your server-side files, like your PHPs. Every user who opens your webpage sees the same PHP, so if 5 users are browsing your page, they are all see the content that index.php has generated for them. The output of your PHP file (a HTML code) will be in their browsers (in the users computer's memory), and you can modify it with jQuery. It will always remain in the memory of the users' computer. So if you want to save something a user typed, you have to send it back to your server and here a PHP can catch it and save it for you. But it's not a good idea to save it to a file, since if 5 users sending back data, you should save 5 separate files for them (and you have to identify all users). But the basics are here:
You have to make a PHP file that can catch your input, save it as ajax.php:
<?php
$fil = fopen("score.txt","a");
$loglinje = "score:".$score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
?>
Then you have to send the data back to the server, so your jQuery code should something like that:
<script>
$(".button").click(function()
{
$(this).addClass("button-clicked");
$(this).siblings(".button").addClass("disabled");
$(this).siblings(".rett").addClass("rett-ved-feil");
$(this).unbind("click");
$(this).siblings(".button").unbind("click");
if($(this).hasClass("rett"))
{
rettVar++;
$.ajax({
url: '/ajax.php',
type: 'post',
dataType: 'json',
data: {
score: rettVar
}
})
.always(function() {
})
.fail(function() {
alert('There is an error occured.');
})
.done(function(result) {
$("#antall-rett").html(rettVar);
$("#score").html(rettVar);
$(this).addClass("button-clicked-riktig");
});
}
});
</script>
So this way the jQuery send back the score to the server, which is save it to you.
I hope it helps, but please consider, this code is only an example. I DO NOT recommend it to use in real-world application, since it has some security backdraws and maybe you should save the values to a database rather than a text file.

Categories

Resources