My colleague and me are having a hard time trying to solve this problem. We have a special kind of webshop, because we have customers and sub-customers. If the person logged in is a sub-customer, we want to show some extra html on our page. This works, but if a sub-customer logs out, and a normal customer logs in, the extra html is still visible, but we don't understand how this is possible. The problem is also vice versa: if the first logged in is a normal user, then logs out, then a sub-customer logs in, the extra html is not visible.
1. loginck.php
//after the user types his e-mail end password, we check if its a normal user or a sub-user.
If normal user then => $_SESSION['multiklant'] = 0;
else sub-user then => $_SESSION['multiklant'] = 1;
else $_SESSION['multiklant'] = 0; //user not found
2. index.php
if ($_SESSION['multiklant'] == 1) {
$userid = $_SESSION['userid'];
echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";
$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}
echo "</select>";
echo "</div>";
}
3.1 logout click on index.php
$("#logout").click(function () {
var lgout = $.get("logout.php");
lgout.done(function (data) {
$(".show-2").trigger("click");
$("#logout").addClass("hidden");
});
});
3.2 logout.php
<?php
session_start();
$_SESSION = array();
session_unset();
session_destroy();
header("Location:index.php");
exit();
?>
As you can see, we used AJAX here, but even without the problem stays. If possible we would like to keep the AJAX, but if not it can be deleted. Also a combination, where the redirect is not in de php but in the javascript part.
Could this be a caching problem? Because if we reload our browser without cache, it al works.
We are searching the internet, including this site already for 6 hours...
Code tested in Chrome on MAC and Internet Explorer 11 on Windows, gives no difference.
Your logout does a header location with exit. In other words: is the $.get('logout.php') done?
Why do you do a redirect serverside? So full page and scripts will be reloaded! And you're waiting for 'done'. Do this:
remove the lines with header and exit from logout.php
After the session is destroyed, the page is ready and the .done callback will be executed.
Look at response header after logout and check "cache-control".
I think problem in cache.
YES!
After searching a long time and trying some of your suggestions (which we are grateful for, I upvoted the most useful ones) we found the solution.
It was after reading this it all came (more) clear. Index.php is our only page with content. So yes, we start a session there, but if we change the session variables afterwards via AJAX, index.php doesn't track those changes.
This is why we tried to refresh the page after logging out, so the sessions variables would be refreshed to. That didn't work. It was until we did also a refresh after logging in also, it al worked, although with some page refresh for the users.
So we put those blocks of code in separate php files and check when needed with AJAX
This is our solution:
1. When the user logs in:
$("#blockleveradressen").load("leveradressen.php");
var testmultiklant = $.get("testmultiklant.php");
testmultiklant.done(function (data){
if(data == 3){
$("#een").removeClass().addClass("col-md-3");
$("#twee").removeClass().addClass("col-md-3");
$("#drie").removeClass().addClass("col-md-3");
}else {
$("#een").removeClass().addClass("col-md-4");
$("#twee").removeClass().addClass("col-md-4");
$("#drie").removeClass().addClass("col-md-4");
}
});
2. leveradressen.php
include "include/session.php";
include "include/MyConnect.php";
if ($_SESSION['multiklant'] == 1) {
$userid = $_SESSION['userid'];
echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";
$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}
echo "</select>";
echo "</div>";
}
3. testmultiklant.php
include "include/session.php";
if ($_SESSION['multiklant'] == 1) {
echo 3;
} else
{
echo 4;
}
4. index.php
<div id="blockleveradressen">
</div>
<div id="een" class="col-md-4">
<label for="datepicker">Leveringsdatum*:</label><br/>
<input type="text" id="datepicker" readonly="readonly"/>
<input type="hidden" id="datepickerAlt" readonly="readonly" visible="false">
</div>
<div id="twee" class="col-md-4">
<label for="timepicker">Leveringstijdstip*:</label><br/>
<input type="text" id="timepicker" class="time"/>
</div>
<div id="drie" class="col-md-4">
<label for="betaalMethode">Betaalmethode*:</label><br/>
<select id="betaalMethode" class="form-control">
<option value="Overschrijving">Overschrijving</option>
<option value="Visa">Visa</option>
<option value="Cash">Cash</option>
</select>
</div>
Just need to clean up the code, but this works. Just learned another lesson: single-paged websites and php (session more specific) are not best friends :-)
Related
In the below code you can see a DIV class="inprg" shows up messages and a couple of buttons on the screen upon the value of database field 'trans_status = ' but user requires to reload the page. How can I make it auto?
<?php
$where="where qu_id={$b_info['qid']} and (trans_status = 'Completed') ";
$order_list=$obj->get_all_records("manage_order",$where,"order_id","DESC");
if(($_SESSION['u_id']==$buyeridaaa || ($_SESSION['u_id']==$s_id)) && !empty($r))
{
$token=$order_list[0]['token'];
$release_flag=$order_list[0]['release_flag'];
$ord_dispute=$order_list[0]['dispute'];
echo '<div class="toolbar"><div class="in_progr">';
if($release_flag=='N' && $ord_dispute=='N')
{
$inprog='<div id="order_status1" class="inprg" style="color:#81CC40">Deposited: '.$order_list[0]['order_amt'] .'₽</div>';
if($_SESSION['u_id']==$buyeridaaa)
{
echo '<form action="" method="post"><input type="hidden" name="tkn" value="'.$token.'">';
echo $dispute_b.'<button type="submit" class="release_btn" name="submit_release" value="1">Release</button>
</form>'.$inprog;
}
else if($_SESSION['u_id']==$s_id)
{
echo $inprog;
}
}
else if ($ord_dispute=='Y') {
echo '<div id="order_status2" class="inprg" style="color:red">Deal disputed!</div>';
}
else
{
echo '<div id="order_status3" class="inprg" style="color:orange">No Deposit!</div>';
}
echo '</div></div>';
}
?>
What you are looking for is called websockets: https://www.google.com/search?q=websockets
Websockets allow your frontend to hook up to your backend and allow your backend to sent messages to frontend on which the frontend can react.
There are multiple libraries and services available to help you establish this. I suggest you first study the technology and available tools.
I am trying to check if a user has taken a quiz before and if he/she has, I want them to be not able to take the quiz again. I implemented the code to do this by using cookies and for some reason my code refuses to stop a user from taking the quiz again. I've been staring at this for a very long time now so help would be nice!
Notes: $_SESSION["index"] is set to 0 initially from a previous page and $_COOKIE['quizTakers"] is an empty array initially. Each Question comes one at a time.
<?php
session_start();
#get array of quizTakers from cookie
$addUser = unserialize($_COOKIE['quizTakers']);
$userN = $_SESSION['username'];
#check if user has taken quiz already and make sure you only check once and not after every question submit
if(count($addUser) != 0 && intval($_SESSION["index"]) == 0 ){
foreach ($addUser as $user) {
if( strcmp($userN,$user) ){
echo "You already took the quiz! <br \>";
echo "<form action=\"changeUser.php\" method=\"post\"> Go Back: <input type=\"submit\"><br \> </form>";
exit();
}
}
array_push($addUser, $userN);
setcookie('quizTakers', serialize($addUser), time()+86400);
echo "loop was entered <br />";
}
#if array is empty(this is should execute the every first time someone takes the quiz
elseif (count($addUser) == 0) {
#add user to array if this is first person taking a quiz yo
array_push($addUser, $userN);
setcookie('quizTakers', serialize($addUser), time()+86400);
echo "cookie added line 29 <br/>";
}
$indexTemp = intVal($_SESSION["index"]);
if(isset($_SESSION["notFirstIndex"])){
#get array of correct answers
$correctAns = $_SESSION["correctAnswers"];
#get particular answer at current index
$currentCorrectAns = intval($correctAns[$indexTemp]) +1;
$userAns = intval($_POST['ans']);
echo "The User picked: ".$userAns." and the correct Answer was: ".$currentCorrectAns."<br/>";
if($userAns == intVal($currentCorrectAns)){
echo " you were correct! <br />";
$_SESSION["totalCorrect"] += 1;
}
else{
echo "you were wrong";
$_SESSION["totalIncorrect"] +=1;
}
}
elseif(!isset($_SESSION['notFirstIndex'])){
echo "Welcome to your quiz, $userN <br />";
echo "You havent answered any questions yet! <br />";
}
?>
<!DOCTYPE html>
<html>
<HR>
</html>
<?php
#When questions are over show results
if($_SESSION["numQuestions"] == $indexTemp){
$_SESSION["index"] = 0;
echo "Your Results are: <br /> ";
echo "Total Questions: ".$_SESSION["numQuestions"]."<br/>";
echo "Total Correct: ".$_SESSION["totalCorrect"]."<br/>";
echo "Total Incorrect: ".$_SESSION["totalIncorrect"]."<br/>";
$percentage = (intval($_SESSION["totalCorrect"]) / intval($_SESSION["numQuestions"])) * 100 ;
echo "Percentage Rightht: $percentage % <br/ >";
echo "<form action=\"process.php\" method=\"post\"> Back to Main screen: <input type=\"submit\"><br \> </form>";
$takers = unserialize($_COOKIE['quizTakers']);
echo $takers[0];
if(count($takers) == 1){
echo "<br />";
echo "You were the first Quiz Taker: <br />";
echo "Total Takers: 1 <br />";
echo "Number Right: ".$_SESSION["totalCorrect"]."<br/>";
echo "Number Incorrect: ".$_SESSION["totalIncorrect"]."<br/>";
echo "Average: $percentage % <br/ >";
exit();
}
exit();
}
$filename = $_SESSION["quizOfTheDay"];
$quizStuff = file($filename);
$ctr =1;
$questionInfo = $quizStuff[$indexTemp];
$questionParse = explode("#", $questionInfo);
#$_SESSION["correctAns"] = $questionParse[2];
#echo $_SESSION["correctAns"]." from line 56 <br />";
$_SESSION['notFirstIndex'] = "true";
$answerChoices = explode(":",$questionParse[1]);
echo "$questionParse[0]? <br />";
?>
<!DOCTYPE html>
<html>
<form action="questions.php" method="post">
<?php
foreach ($answerChoices as $answerChoice) {
echo "<input type='radio' name='ans' id='q1' value=".$ctr."> <label for='q1'>".$answerChoice."</label> <br />";
$ctr +=1;
}
$_SESSION["index"] = $indexTemp +1;
?>
<input type="submit" name="submit" value="GO!">
</form>
</html>
Before the cookie is set, $_COOKIE['quizTakers'] doesn't exist, and when you call unserialize() on this you set $addUsers to false. Then when you try to do array_push($addUser, $userN);, this fails because $addUser isn't an array, so $addUser is still false. Then you put this into the cookie.
The next time the user runs the script, you read false from the cookie, and the username isn't found in this, so you don't stop the user from taking the quiz again.
You're making this much more complicated than it needs to be. You don't need to put an array into the cookie, because cookies aren't shared by all the users. Just set a cookie to a simple string and test whether the cookie is set.
if (isset($_COOKIE['took_quiz'])) {
echo "You already took the quiz! <br \>";
echo "<form action=\"changeUser.php\" method=\"post\"> Go Back: <input type=\"submit\"><br \> </form>";
exit();
}
setcookie('took_quiz', 'true', time()+86400);
As others pointed out, users can get around this by clearing cookies. So if you need something more secure, you need to implement a login system and use a database or file to track which users have already taken the quiz.
I have not read your code, but did you foundamentally understand the concept of a cookie/session?
A cookie will store data at the browser and sends it everytime the website is requested. A session, will store the data on the server, but will store a cookie a the clients side to identify the user on subsequent requests.
So the user can simple wipe the cookies (in both cases) and the server does not know, that this user has ever taken the quiz.
What you can try is a combination of IP address and browser metric, but beware that IP adresses can change (very quick ;) )
Cookies could be erased by the user and you wouldn't know if they did your quiz or not .
You may need to force people to register to gain access to your quiz if you want a permanent way to know if they completed them or not as cookies can easily be wiped.
The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!
Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)
action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that
You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.
Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.
I have a quick question about this fade out div. I use facebox, and after the submit, and it shows an error it'll show this:
http://puu.sh/1uPnF
however I want that to fade away, after they've caught that message. On my AJAX handler for the submit form, this is the PHP code:
<?php
require_once('....');
$form_name = $_GET['form_name'];
$form_comment = $_GET['form_comment'];
$date = date('Y-n-j');
$ip = $_SERVER['REMOTE_ADDR'];
if($form_name == '') {
echo("<div class='alert alert-error-x'>Don't forget to enter a name, as we need to identify who's commenting on this article!</div>");
} else if($form_comment == '') {
echo("<div class='alert alert-error-x'>Please do not leave the comment field blank, we want to know what you're saying!</div>");
} else {
mysql_query("INSERT INTO comment (id, articleid, name, comment, date, ip) VALUES (NULL,'{$_GET['id']}','{$form_name}','{$form_comment}','{$date}','{$ip}')");
// output comment
echo "<div class='alert alert-success-x'>Posted by <strong>$form_name</strong> on <strong>{$date}</strong>$form_comment</div>";
}
?>
This is where the output of what would be submitted, on the article.php:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); $comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
<div id="new_comment"></div>
<div class="article-comment">
Posted by <b><?php echo $row['name'] ?></b> on <b><?php echo $row['date'] ?></b>
<br />
<?php echo $row['comment'] ?>
</div>
<?php } ?>
</div>
</body>
</html>
Now I tried adding the below code in the core.js file, which is located on my site at krissales.com
$(window).bind("load", function() {
$('#new_comment').fadeOut(4000);
});
However it did not work. If you want to test the demo, then check it out at: http://www.krissales.com/#/media/30.This-is-a-new-article-for-Testing!
What is it that I'm doing wrong, please?
Thanks!
If you're using AJAX, I suggest you use jquery's ajax method (http://api.jquery.com/jQuery.ajax/) to make the call to your PHP file.
Then, use the success callback function of that method to show the correct response.
Hiding the response can then simply be done by fading out the div (with a delay if you want that).
if ($('#new_comment').length > 0)
{
$('#new_comment').delay(4000).fadeOut();
}
You are now trying to fade out the message on window load, but since you're using AJAX, there is no page reload happening.
Hope this helps you!
Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.
First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.
Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});
you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()