This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to display the correct page number?
I have a piece of code below where it determines which assessment the user is in and the assessment number the user is currently on:
<h1>CREATING QUESTIONS AND ANSWERS: ASSESSMENT <?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
So on the browser this could read for example:
CREATING QUESTIONS AND ANSWERS: ASSESSMENT 1 OF 4
Now below I have a submit button:
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
Now if the user clicks on the button, it will show a confirmation box and if the user clicks OK, for the confirmation, then it will submit the page and what is suppose to happen is that it adds a number to the assessment to indicate that the user is on the next assessment.
SO FOR EXAMPLE:
If it says this on the page:
CREATING QUESTIONS AND ANSWERS: ASSESSMENT 1 OF 4
If the user submits the page and confirms, then it should now say this:
CREATING QUESTIONS AND ANSWERS: ASSESSMENT 2 OF 4
This is because the user is on the next assessment now.
But the problem is that it is not adding the number at all when the user submits the page. It just stays at '1' and doesn't add up. So instead of doing the above it is doing the below:
If it says this on the page:
CREATING QUESTIONS AND ANSWERS: ASSESSMENT 1 OF 4
If the user submits the page and confirms, then it still says:
CREATING QUESTIONS AND ANSWERS: ASSESSMENT 1 OF 4
This is obviously incorrect.
So my question is that does anyone know why it is not adding up the number? I know that the php is not the problem because I tested my code and what I have found is that if there is no jquery validation() function, then the code works fine and it adds the number up from 1 onwards.
But if I include the jquery validation() function which is needed, then it doesn't add the number at all and just stays at 1.
Can anybody help and fix this problem?
You can test the application yourself here, just follow steps below:
When you open link type in number 5 in the textbox and submit page
When you have navigated to next page you see on top it states CREATING QUESTIONS AND ANSWERS: ASSESSMENT 1 OF 5. Now scroll to bottom of page and click "Submit Details" button and confirm the confirmation box.
You will see that the heading still states CREATING QUESTIONS AND ANSWERS: ASSESSMENT 1 OF 5 and not CREATING QUESTIONS AND ANSWERS: ASSESSMENT 2 OF 5.
Below is relevant code so you know what the code is:
<?php
session_start();
if(isset($_POST['sessionNum'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['sessionNum'];
$_SESSION['sessionNum'] = intval($_POST['sessionNum']);
$_SESSION['sessionCount'] = 1;
}
elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
$_SESSION['sessionCount']++;
}
$sessionMinus = $_SESSION['sessionCount'];
if ($sessionMinus == $_SESSION['initial_count']){
$action = 'create_session2.php';
}elseif($sessionMinus != $_SESSION['initial_count']){
$action = $_SERVER['PHP_SELF'];
}
?>
<script type="text/javascript">
function validation() {
var _qid = "";
var _msg = "";
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
_qid = $("td.qid",this).text();
_msg = "You have errors on Question Number: " + _qid + "\n";
$(".textAreaQuestion",this).each(function() {
if (!this.value || this.value.length < 5) {
alertValidation += "\n\u2022 You have not entered a valid Question\n";
}
if (alertValidation != "") {
return false; //Stop the each loop
}
});
if(alertValidation != ""){
return false;
}
});
if (alertValidation != "") {
alert(_msg + alertValidation);
return false;
}
return true;
}
function showConfirm(){
var confirmMsg=confirm("Make sure that your details are correct, once you proceed after this stage you would not be able to go back and change any details towards Questions, Options and Answers for your Session." + "\n" + "\n" + "Are you sure you want to Proceed?" + "\n" );
if (confirmMsg==true)
{
submitform();
}
}
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize() ,function(data){
var QandAO = document.getElementById("QandA");
QandAO.submit();
});
alert("Your Details for this Session has been submitted");
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<h1>CREATING QUESTIONS AND ANSWERS: ASSESSMENT <?php echo $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?></h1>
<p><input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" onClick="myClickHandler(); return false;" /></p>
</form>
<script type="text/javascript">
function myClickHandler(){
if(validation()){
showConfirm();
}
}
</script>
After a submit this code is run:
if(isset($_POST['sessionNum'])){
...
$_SESSION['sessionCount'] = 1;
}
$sessionMinus = $_SESSION['sessionCount'];
and the this is displayed in the browser:
<h1>
CREATING QUESTIONS AND ANSWERS: ASSESSMENT
<?php $sessionMinus ?> OF <?php echo $_SESSION['initial_count'] ?>
</h1>
The result of $sessionMinus is always 1 !!
I don't think this is a valid statement:
$_SESSION['sessionCount']++;
I think you need to set it like so:
$_SESSION['sessionCount'] = $_SESSION['sessionCount'] + 1;
Related
Okay people, what I am trying actually trying to achieve is, to create a chat box something similar to fb without refreshing the page. I have two tables in my database(phpmyadmin) where the first table, i store 2 users chat id(unique) and later save their message in another table so that i will be able to retrieve their chat history just by their unique id.
So I was able to send their Id(unique) by using get method to send the unique ID to the second div and then run through the database using php and display their conversation.
So how can i do it in ajax so that the page does not refreshes guys ? Some guide on that please ? I have been trying to google for it but i cant find a way simply because i do not know ajax much.
The purpose of me wanting it to not refresh the page is because i am using Jquery to hide and show the chat conversation. When the page refreshes, the conversation disappears. Im sorry if my explanation is not on point, hopefully somebody understands my problem and guide me in this :D
So here are my codes ...
This code is in my first div. It basically displays all the users who I have chatted with before...
<div>
<ul style="list-style-type: none;">
<?php
include 'connectDB.php';
//retrieve all the message history of yours from the PrivateMessage table
$query = "SELECT * FROM `messagecheck` WHERE `sender_a` = '$userId'
OR `sender_b` = '$userId';";
$result = mysqli_query($dbconnect,$query);
if(mysqli_num_rows($result) > 0)
{
//if exist, display the history
while($row = mysqli_fetch_assoc($result))
{
?>
<a href="Item_v1.php?msgId=<?php echo $row['exist']?>">
<li style="color:black; width:100%; padding-top:5px" >
<input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" >
<?php
//if the sender_a id is not my id, display the name
//if sender_a is my id, then display sender_b
//Because we dont want to see our name in the chat History
if($row['sender_a'] != $userId)
{
$senderName = $row['sender_a'];
include 'connectDB.php';
$nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
$Searchresult = mysqli_query($dbconnect,$nameSearch);
$Searchrow = mysqli_fetch_assoc($Searchresult);
echo $Searchrow['fName'] ." ". $Searchrow['lName'];
}
else
{
$senderName = $row['sender_b'];
include 'connectDB.php';
$nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
$Searchresult = mysqli_query($dbconnect,$nameSearch);
$Searchrow = mysqli_fetch_assoc($Searchresult);
echo $Searchrow['fName'] ." ". $Searchrow['lName'];
}
?>
</li>
</a>
<?php
}
}
?>
</ul>
</div>
So basically when i click the names which will be in the < li > tag, it should be posting the messages in another div(Which is the div below)...
<!-- //Message Content! -->
<div style="width:100%;max-height: 300;border: 2px solid #1F1F1F;overflow: auto;">
<?php
if($_GET)
{
$msgId = $_GET['msgId'];
}
if(!empty($msgId))
{
include 'connectDB.php';
$collectMsgQuery = "SELECT * FROM `privatemessage` WHERE `existing_id` = $msgId";
$MsgResult = mysqli_query($dbconnect, $collectMsgQuery);
if(mysqli_num_rows($MsgResult) > 0)
{
while($Msgrow = mysqli_fetch_assoc($MsgResult))
{
if($userId == $Msgrow['from_who']){
?>
<h4 class="ifMe"><span class="ifMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
<?php
}else if ($userId == $Msgrow['to_who']) {
?>
<h4 class="notMe"><span class="notMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
<?php
}
}
}
}
?>
</div>
P.S : I'm not really sure how to work with ajax so that is why i am posting it here. Any help would be great! Thanks in advance ! :D
Working with ajax, at the beginning, can be very frustrating. You should start with more simple task, simply to understand what you're working with.
Start with something like this, a simple request that send two numbers to the server and then alert the sum
ajax_request.php
<?php
$num1 = isset( $_GET[ "num1" ] ) ? $_GET[ "num1" ]: 0;
$num2 = isset( $_GET[ "num2" ] ) ? $_GET[ "num2" ]: 0;
echo $num1 + $num2;
index.html
<html>
<head>
<script src="jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$( "#calculate" ).click(function(e) {
e.preventDefault();
$.ajax({
url: 'ajax_request.php',
data: $( "#form" ).serialize(),
success: function( data ) {
alert( data );
},
error: function() {
alert( "Something went wrong" );
}
});
});
});
</script>
</head>
<body>
<form id="form">
Num1: <input type="text" name="num1" /><br />
Num2: <input type="text" name="num2" /><br />
<input type="submit" id="calculate" />
</form>
</body>
</html>
Open index.html (download the jQuery library), fill the two numbers and click the button.
You can test the "Something went wrong", simply put a wrong url (ajax_requestx.php instead of ajax_request.php).
From here, you can study "ajax" and "jQuery" to understand better how this work.
The concept is this: you stop the form to be sent (e.preventDefault()) and instead send the form in "asyncronous" way, making javascript send the request to the server without changing the page; in the "success" function you can analyze the string sent back from the server and do something with it. All done by javascript
Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.
I have searched a lot but cannot find a solution yet. Hope anyone can help me with it, I will really appreciate.
I use a php news page with session. PHP script displays 10 news and if there is more news, visitor suppose to click "Next" button (I try to make it work with tag, but it doesn't work with usual submit button either). Page refresh using same script adding a value to page. Everything seemed to work except session. $_SESSION['page'] does not add value. I always come back to Page1.
<?php session_start();?>
<?php
if(isset($_SESSION['page']) && isset($_POST['next'])){
$_SESSION['page']++;
}
if(isset($_SESSION['page']) && isset($_POST['previous'])){
$_SESSION['page']--;
}
else{
$_SESSION['page']=1;
}
....//code reading file with news, counting values etc. that work good
//I tried several options:
//Option:1
if ($l == "en") {
echo '<p class="sider_link">Page: '.$_SESSION['page'].'. Unread news: '.$news_left;
echo '<form action="../en/news.php" method="post">';
echo '<a class="sider_link" href="#" name="next" onclick="this.form.submit()">Next Page</a></form></p>';
}
//Option:2
if ($l == "en") {
echo '<p class="sider_link">Page: '.$_SESSION['page'].'. Unread news: '.$news_left;
echo '<form action="../en/news.php" method="post">'
echo '<input type="hidden" name="next" value="yes" />';
echo '<a class="sider_link" href="#" onclick="this.form.submit()">Next Page</a></form></p>';
}
Your first statement works, page is increment. But after the second statement is false, the else condition is called. Page is set to one. To sum up you have an error in your condition.
if(isset($_SESSION['page']) && isset($_POST['next'])){
$_SESSION['page']++;
}
if(isset($_SESSION['page']) && isset($_POST['previous'])){
$_SESSION['page']--;
}
else{
$_SESSION['page']=1;
}
To
if(isset($_SESSION['page']) && isset($_POST['next'])){
$_SESSION['page']++;
}
else if(isset($_SESSION['page']) && isset($_POST['previous'])){
$_SESSION['page']--;
}
else{
$_SESSION['page']=1;
}
I have an edit_ticket_check.php page like this:
<form name="frm" action="edit_ticket_asso.php" method="post" onSubmit="return validt(frm)">
<table frame=box align=center bgcolor="9966FF">
<b><h2>Enter Ticket Information</h2></b>
</table>
</form>
Then some boxes like this:
<tr><td><font color="BLACK">Ticket Status:</font></td>
<td>
<?php
echo "<select name=\"ticket_status\">";
echo "<option size =15 selected>Select</option>";
if(mysql_num_rows($result4))
{
while($row = mysql_fetch_assoc($result4))
{
echo "<option>$row[ticket_status]</option>";
}
}
else {
echo "<option>No Status Present</option>";
}
?>
</td>
The input values go to a second edit_ticket.php page where it enters the value in a MySQL database.
if($_POST['submit']=="Insert")
{
$ticket_no=$_POST['ticket_no'];
if ( #$_SESSION[username] == 'admin')
{
$assigned_to=$_POST['emp_name'];
}
else
$assigned_to = #$_SESSION[userid][0];
$reassigned_to_team=$_POST['reassigned_to_team'];
$ticket_status=$_POST['ticket_status'];
$comment=$_POST['comment'];
if($ticket_no!=NULL&&$assigned_to!=NULL&&$comment!=NULL)
{
$query1=mysql_query("select count(ticket_no) as total from ticket where ticket_no='$ticket_no';");
$row = mysql_fetch_array($query1);
if ($row["total"]>"0")
{
$query2="UPDATE ticket SET ticket.assigned_to='$assigned_to', ticket.reassigned_to_team='$reassigned_to_team', ticket.ticket_status='$ticket_status', ticket.comment='$comment' WHERE ticket.ticket_no='$ticket_no'";
$result1=mysql_query("$query2");
}
}
}
Now after this I want that if ticket status = 'pending' then a new pop up window will come up and take a time value and then update the time value of ticket by the newly entered time.
For the pop up window I have this code:
<html>
<body>
<p>Click the button to add resolution time with pending ticket.</p>
<button onclick="myFunction()">Pending</button>
<p id="demo"></p>
<script type="text/javascript">
function myFunction()
{
var x;
var name=prompt("Please enter Resolution Time","2099-12-31 23:59:59");
if (name!=null)
{
x="resolution_time " + name ;
document.getElementById("demo").innerHTML=x;
}
}
</script>
Now I can't connect these two pages and I'm also unable to pass the values from the new pop up window to old window.
How can i do this?
Since PHP is a server-side language so it can't be dyanamic like JavaScript which is a client-side language, do you have any better idea to do this other way round?
thank you..
Your landing page (the one that your form processor page, edit_ticket.php should redirect to when it's finished) should accept a parameter in the url. Based on that, you can write javascript in the new page to decide whether or not to open the pending window.
For example: at the end of edit_ticket.php,
header("location: landing.php?pending=1");
and then in pending:
<?php
if (isset($_GET['pending']) && $_GET['pending'] ==1){
?><script type='text/javascript'>
window.open('yourpopup.html');
<?php
}
?>
I'm trying to implement a form that utilizes jquery's post feature to dynamically update the database. What I'm realizing is that after the user clicks the "update" button, the success function is called back just fine with a "Update successful" message.
The issue I have for the stackoverflow world is why on subsequent clicks (w/o refreshing the page) I'm not getting this same success message. Also, ironically my database is being updated, so I know the AJAX call is going through.
I've posted my code below:
JS
var TEAM = {
update: function() {
var form_data = $('form').serialize();
$.ajax({
type: "POST",
url: "../manager/edit_team.php",
data: form_data,
error: function() {
$('#status').text('Update failed. Try again.').slideDown('slow');
},
success: function() {
$('#status').text('Update successful!');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
},
cache: false
});
}
}
// jQuery Code for when page is loaded
$(document).ready(function()
{
$("#update").on("click", function() {
TEAM.update();
});
});
PHP (I welcome any other comments as well)
require '../includes/config.php';
include '../includes/header.html';
// autoloading of classes
function __autoload($class) {
require_once('../classes/' . $class . '.php');
}
// Site access level -> Manager
$lvl = 'M';
// Assign user object from session variable
if (isset($_SESSION['userObj']))
{
$manager = $_SESSION['userObj'];
}
else
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Establish database connection
require_once MYSQL2;
// Assign Database Resource to object
$manager->setDB($db);
// Authorized Login Check
if (!$manager->valid($lvl))
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Check for a valid game sch ID, through GET or POST:
if ( (isset($_GET['z'])) && (is_numeric($_GET['z'])) )
{
// Point A in Code Flow
// Assign variable from myteams-m.php using GET method
$id = $_GET['z'];
}
elseif ( (isset($_POST['z'])) && (is_numeric($_POST['z'])) )
{
// Point C in Code Flow
// Assign variable from edit_team.php FORM submission (hidden id field)
$id = $_POST['z'];
}
else
{
// No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
$team = new ManagerTeam();
$team->setDB($db);
$team->setTeamID($id);
$team->pullTeamData();
$flag = 0;
echo $flag . "<br />";
// Confirmation that form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{ // Point D in Code Flow
// Assume invalid values:
$tname = FALSE;
// Validate team name
if ($_POST['tname'])
{
$tname = $_POST['tname'];
}
else
{
echo '<p class="error"> Please enter a team name.</p>';
}
// Validate about team information
if ($_POST['abouttm'])
{
$abtm = trim($_POST['abouttm']);
}
else
{
$abtm = '';
}
// Check if user entered information is valid before continuing to edit game
if ($tname)
{
if($team->editTeam($tname, $abtm) == True)
{
echo '<p>Team was successfully updated</p>';
$flag = 1;
}
else
{
echo '<p>No changes were made</p>';
$flag = 2;
}
}
else
{ // Errors in the user entered information
echo '<p class="error">Please try again.</p>';
}
} // End of submit conditional.
echo $flag . "<br />";
// Point B in Code Flow
// Always show the form...
// Get team name attribute
$team->pullTeamData();
$teamname = $team->getTeamAttribute('tmname');
$about = $team->getTeamAttribute('about');
if ($teamname != '') // Valid user ID, show the form.
{
// Headliner
echo '<h2>Edit Team</h2>';
// Create the form:
echo '
<div id="EditTeam"></div>
<div id="Team">
<fieldset id="TeamDetails">
<legend>Edit Team</legend>
<form method="post" id="information">
<p id="status"></p>
<input type="hidden" name="z" value="' . $id . '" />
<p>
<label for="tname">New Team Name:</label><br/>
<input type="text" name="tname" id="tname" size="10" maxlength="45" value="' . $teamname . '" />
</p>
<p>
<label for="abouttm">Team Information:</label><br/>
<textarea id="abouttm" name="abouttm" cols="30" rows="2">"' . $about . '"</textarea><br />
<small>Enter something cool about your team.</small>
</p>
<p>
<input type="hidden" name="id" id="id">
<input type="button" value="update" id="update" />
</p>
</form>
</fieldset>
</div>';
}
else
{ //Not a valid user ID, kill the script
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
// Close the connection:
$db->close();
unset($db);
include '../includes/footer.html';
?>
You'll notice I also have a $flag defined to help with the debugging, but ironically it outputs 0 no matter the number of clicks to the "update" button. So there's no indication that the database is being updated, yet when I check the tables it certainly is.
I appreciate any help or pointers. Thanks,
#status message is not showing because you've hidden it by slideUp(), to show it again you need to slideDown() them.
success: function() {
$('#status').text('Update successful!');
-ADD-> $('#status').slideDown('slow');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
Do it same way as you have done in error handler:
success: function(){
$('#status').text('Update successful!').slideDown('slow');
...
It seems that you know it already and just forgot it...
Other method that may be useful is stop() to make sure that previous animation is stopped when new one is starting., especially important when using long timeouts/animations.
(useful = can prevent other problems with visibility and makes sure that messages does not start jumping in and out)
(long = somewhere around 0,5-1,5 sec or more, if during this time can happen something else then it is long...)
For example, this will clear fx queue, finish running animation immediately and slideUp():
$('#status').stop(true, true).slideUp('slow');
You also asked suggestions for other parts of code
If you are using same code at least twice or if it is general method that could be reused make it reusable:
function redirect_to( $page ) {
session_unset();
session_destroy();
$url = BASE_URL . $page;
ob_end_clean();
header("Location: $url");
exit();
}
if ($condition == true) {
redirect_to( 'index.php' );`
}