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
}
?>
Related
I need to make drop down list as a link to different pages. How do I do that using PHP, MySQL and HTML.
<?php
mysql_connect('localhost','root','');
mysql_select_db('test');
$sql="select first_name from users";
$result=mysql_query($sql);
echo "<select First_name=''>";
echo "<a href='index.html'>";
while($row=mysql_fetch_array($result)){
echo ":<option value='".$row['first_name']."'>".$row['first_name']."</option>";
}
echo"</a>";
echo"</select>";
?>
You can't use links on the option tag, in order to do that, you need to use javascript.
You can try to do something like this:
echo "<select name=\"First_name\" onchange=\"document.location='?'+this.value\">";
PHP is a server-side script and does not manipulate a page after a user has adjusted it. Like real time. Only javascript and others do that. PHP creates a page with what you want to see but if you need to change something bases on a dropdown use java. Here is a function that can do that. It unhides a div tag that can have your info you need.
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('dropdown');
var divtag1 = document.getElementById('divtag1');
var divtag2 = document.getElementById('divtag2');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 1) {
divtag1.style.display = 'block';
}
if(eSelect.selectedIndex === 2) {
divtag2.style.display = 'block';
}//or if you want it to open a url
if(eSelect.selectedIndex === 3) {
window.open("https://yourwebsite.com", "_NEW");
}
}
}
</script>
echo "<div id=\"divtag1\" style=\"display:none;\">/*your code*/
</div>";
echo "<div id=\"divtag2\" style=\"display:none;\">/*your code*/
</div>";
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
I have two innoDB tables in my database named customers and vessels. I also have a form with 2 select boxes one having the column: company_name of table: customers as options, and the other having the column: vessel_name of table: vessels.
What i want to do is make the options of the 2nd select box populate according to the customer's company_name chosen in the 1st select box.
Finally please take into consideration that i am a complete newbie in Javascript and jQuery and thats why i am asking here how can i achieve the above result.
The form:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
The php to make the above form work :
<?php
// For customers
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if($pelat = $db->query($sqlpelates)) {
$pelates = array();
while($pelate = $pelat->fetch_object()) {
$pelates[] = $pelate;
}
$pelat->free();
}
// For vessels
$sqlploia = "SELECT * FROM vessels ORDER BY vessel_name";
if($plo = $db->query($sqlploia)) {
$ploia = array();
while($ploi = $plo->fetch_object()) {
$ploia[] = $ploi;
}
$plo->free();
}
?>
UPDATE: Below is the single .php page where i am trying to achieve the above result:
<?php
require 'db/connect.php';
//check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
$pelates = array();
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
}
// modify the query to filter out only what your ajax request wants
$where = $ajax ? ' WHERE company_name="'.$_POST['companyName'].'"' : '';
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
$ploia = array();
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
if ($ajax) {
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client wants to know
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="jquery.js">
// Your code goes here.
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://prinseapals-marine.com/filing/drop_down.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
</script>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
FINAL-UPDATE :
test.php:
<?php
require 'db/connect.php';
$cus = array();
if($cterm = $db->query("SELECT * FROM `customers`")) {
while($cterm2 = $cterm->fetch_object()) {
$cus[] = $cterm2;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form id="form1" name="myform">
<select name="selection" onchange="load('bdiv', 'test2.php');">
<?php
foreach($cus as $c) {
?>
<option value="<? echo $c->company_name ?>"><? echo $c->company_name ?></option>
<?php
}
?>
</select>
<div id="bdiv"></div>
</form>
</body>
</html>
test.js:
function load (thediv, thefile) {
// body...
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile+'?selection='+document.myform.selection.value, true);
xmlhttp.send();
}
test2.php:
<?php
require 'db/connect.php';
if (isset($_GET['selection'])) {
# code...
$selection = $_GET['selection'];
}
$ves = array();
if ($vterm = $db->query(
"SELECT `vessel_name` FROM `vessels` WHERE `company_name` = '$selection'")) {
while ($vterm2 = $vterm->fetch_object()) {
$ves[] = $vterm2;
}
} else {
echo 'Please type a customer name.';
}
?>
<select>
<?php
foreach($ves as $v) {
?>
<option value="<?php echo $v->vessel_name ?>" ><?php echo $v->vessel_name ?></option>
<?php
}
?>
</select>
This is not the first time I see this asked but I will dive in
Warning: this answer has javascript, with jQuery. I will also append a php file afterwards with some changes to allow the same script to be called for the ajax request
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://localhost/test/stackoverflow.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
The logic behind the js code is to allow user interaction. When the user makes a selection a request is fired to the server and the response is processed in the client and populates your 2nd <select>
Now, a modified version of your php script (warning: this works with the template I append next)
<?php
// your model, check for whitespaces outside php tags, do not allow output yet
require 'db/connect.php';
// check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// required for the template
$pelates = array();
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
} else {
// modify the query to filter out only what your ajax request wants
$where = ' WHERE company_name="'.$_POST['companyName'].'"';
// required for the ajax request
$ploia = array();
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client want's to know
exit;
}
?>
Next comes a modified version of your html template
<!DOCTYPE html>
<html>
<head>
<title>Your title</title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name"><?php
foreach($pelates as $p) echo '<option value="'.$p->company_name.'">'.$p->company_name.'</option>';
?></select>
<!-- leave empty, we will populate it when the user selects a company -->
<select name="vessel"></select>
</form>
<!-- add jQuery lib here, either your own or from a CDN; this is google's version 2.0.3 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- The code should be in a seperate file, load here if you want (but after jQuery lib) -->
<script src="your/javascript/file.js"></script>
</body>
</html>
Ok, now some pointers
you should be carefull with the php script I left there, there are other ways of doing what I intended which are cleaner and easier to maintain
the javascript is not the best, there are better solutions out there so be sure to check those out as well
If you do not understand parts of any of the scripts don't hesitate to ask
Beware any whitespace, do not allow any output before the php script, this is very important. All output should be left to the template
I hope this has been helpfull
Use ajax for this, Pass your company id to the javascript
<script>
function showCustomer(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true); // Pass value to another page Here->test
xmlhttp.send();
}
</script>
<select name="company_name" onchange="showCustomer(this.value)">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<div id="myresult">
</div>
Now On test.php Simply Call Value & put select box,
<?php
$q = $_GET['q'];
// Here fetch values for particular q(company name)
// put select box
Can i write some code to execute while my check box is checked in my php code..
my declaration of check box is...
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>
i thought to perform a function called check() while clicking the check box..
<script type="text/javascript">
function check(cb)
{
if($("input[type=checkbox]:checked"")
{
//my functionality and operations
}
}
But its not working, how can i perform the onclick event in the Checkbox's action..
First of all, there's a mistake. It should be .is(":checked").
function check(cb)
{
if($(cb).is(":checked"))
{
//my functionality and operations
}
}
And the HTML should be:
<input type="checkbox" onclick="check(this);" />
Or, if you wanna invoke a PHP Function after clicking on Checkbox, you need to write an AJAX code. If this is the case, in your if condition, and checked condition, you can call a PHP file, that calls only this function.
function check(cb)
{
if($(cb).is(":checked"))
{
$.getScript("clickCheckbox.php");
}
}
And you can write JavaScript plus PHP in the clickCheckbox.php file, say something like this:
clickCheckbox.php
<?php
header("Content-type: text/javascript");
unlink("delete.png");
echo 'alert("Deleted!");';
?>
Once you click on the checkbox, and if the state is checked, it gives out an AJAX call to this PHP file, where you are deleting a file delete.png and in the echo statement, you are outputting a JavaScript alert, so that you will get an alert message saying Deleted!.
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
Where your form has id myform
use
if ($('#checkbox').is(':checked'))
or inside an event
$('#checkbox').click(function(){
if ($(this).is(':checked')){
//your routine here if checked
}else{
//routine here if not checked
}
});
You can put like this:
Include the column checked in your table with default value NO.
Then after your SELECT statement show the array.
page1.php
<input type=checkbox value="<?php $row['checked']?>" onclick="location.href = 'update.php?id=<?php echo $row['id']; ?>&checked=<?php if ($row['checked'] == 'YES') { ?>NO<?php } else {?>YES<?php } ?>';" <?php if ($row['checked'] == 'YES') { ?> checked <?php } ?>>
update.php
<?php include('server.php'); ?>
<?php
$id = $_GET['id'];
$checked = $_GET['checked'];
if(isset($_GET['id']))
{
$sql = "UPDATE table SET
checked = '$checked'
WHERE `id` = '$id' ";
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error updating record: " . $conn->error;
}
header('location: page1.php');
}
?>
Try this one
<input id="checkbox" name="click" type="checkbox" onclick="check()"/>
//in js
if( $('input[name=checkbox]').is(':checked') ){
// your code
}
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;