Sending quiz answers using a php form - php

I have forms which work fine. I have a quiz which works fine.
When I incorporate the two they don't work fine :(
The quiz works as a quiz but it wont send it out using php to my email address.
Here is a bit of my code:
<head>
<script>
CorrectAnswers = new Array();
CorrectAnswers[0]=1;
CorrectAnswers[1]=1;
CorrectAnswers[2]=1;
CorrectAnswers[3]=2;
macrightchar='YES';
macwrongchar='NO';
winrightchar='YES';
winwrongchar='NO';
var platform = 'win'
if (navigator.appVersion.indexOf('Mac') != -1) {platform = 'mac'}
if (platform == 'mac') {
rightchar = unescape(macrightchar)
wrongchar = unescape(macwrongchar)
}
else {
rightchar = unescape(winrightchar)
wrongchar = unescape(winwrongchar)
}
function CheckAnswer(){
var i = 0;
var TotalCorrect = 0;
var x = 0;
var Score = 0;
for (i=0; i<CorrectAnswers.length; i++){
if (document.QuizForm.elements[i*2].selectedIndex == CorrectAnswers[i]){
document.QuizForm.elements[(i*2)+1].value = rightchar;
TotalCorrect++;
}
else{
document.QuizForm.elements[(i*2)+1].value = wrongchar;
}
}
Score = Math.floor((TotalCorrect*100)/CorrectAnswers.length);
document.CheckForm.ScoreBox.value = Score + '%';
}
</script>
</head>
<body>
<form name="QuizForm" accept-charset="utf-8" method="post" action="forms/quiz/_process.php" onSubmit="return validate.check(this)">
<table class="widthOneHundredPercent">
<tr>
<td class="tableCellFloat columnOne" valign="top">
<label for="Big_Media_offers_a_great_multiplatform_tool">Big Media offers a great multiplatform tool</label>
</td>
<td class="tableCellFloat columnTwo" valign="top">
<select name="0">
<option>???</option>
<option>True</option>
<option>False</option>
</select>
<td valign=top>
<input type="text" name="1" size=2 maxlength=2>
</td>
</td>
</tr>
<tr>
<FORM name="CheckForm">
<td align="center">
<font face="Geneva,Arial"><input type="button" VALUE="Check" onClick="CheckAnswer()"> Your score is <input type=text name="ScoreBox" size="4" maxlength="4"></font>
<center><input type="submit" value="Submit Form" /></center>
</form>
When submit is pressed it will change the end of my file name in the address bar from quiz.php to quiz.php?ScoreBox=75%25. So it takes my correct answers and wrong answers.
I need the quiz to show a live right and wrong answers when check scores is clicked but I also need to send the results using PHP.
If I'm going at it completely wrong perhaps someone can point me in the right direction to start fresh.
Regards.

Few things I notice here:
QuizForm doesn't have a submit button and does not appear to be submitted dynamically (may just not be shown). Perhaps this form and CheckForm can be combined.
CheckForm doesn't have a method defined, which is why the submit puts a query string on it
The score is being submitted instead of the raw answers. Perhaps this is desired behavior, but it leaves the ability for someone to just submit they got a great score.
The answer could be as simple as moving the submit button from CheckForm to QuizForm.

Try adding a closing <form> tag for 'QuizForm' before you open 'CheckForm'.
[edit]Actually, QuizForm doesn't seem to have a submission method.

Related

update list with jquery & ajax [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i make a list with php & jquery which shows every row in my database.
i want to add this list an update button. when user clicks on a row, the row will expand and the button will become visible. and the text on that row will go in a textbox.
and my question is, how can i update the text when user click on the button in that row? first i thought, i could put a form in every row.. but i think that's a terrible solution.
can you suggest me an example or source for what i want to do?
Questions asking for code must show the code you've tried. Since you didn't give any code, I'll give a high-level answer:
Attach an event handler to the button (or probably actually to the table and use delegation).
In the the event handler, use jQuery traversal functions to find the row to which the button belongs.
Once you have a reference to the row, use jQuery traversal functions to find the inputs in the row.
Get the values and use ajax to update the database.
This is essentially what you need to do
jsFiddle (all working except AJAX)
Review the above jsFiddle and you can see how the first part of your question will work.
The values will be updated in the database via AJAX, and the code block is present in the jsFiddle example, but jsFiddle cannot demonstrate AJAX so you can't see it in action there.
However, if you copy/paste the following into two files (three if you break out the javascript into its own file), and edit it to match your own database, then you can see it in action.
Two files are required:
One: index.php (or whatever you wish to call it)
Two: my_php_processor_file.php (if change this name, must also change in the AJAX code block in the javascript
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
//Global var goes here:
editRow = 0;
$(document).ready(function() {
$('#msgbox').dialog({
autoOpen:false,
width:400,
modal:true,
buttons: {
Submit: function() {
var mfn = $('#mfn').val();
var mln = $('#mln').val();
var mem = $('#mem').val();
$('table').find('tr').eq(editRow).find('.fname').val(mfn);
$('table').find('tr').eq(editRow).find('.lname').val(mln);
$('table').find('tr').eq(editRow).find('.email').val(mem);
/*
//Now do the ajax transfer to the server
$.ajax({
type: 'POST',
url: 'my_php_processor_file.php',
data: 'user_id=' +editRow+ '&first_name=' +mfn+ '&last_name=' +mln+ '&email_addy=' +mem,
success:function(recd){
$('#alert').html(recd);
$('#alert').dialog('open');
}
}); //END ajax code block
*/ //Now, close the dialog -- doesn't happen automatically!
$(this).dialog('close');
}, //END Submit button
Cancel: function() {
$(this).dialog('close');
} //END Cancel button
} //END all buttons
}); //END msgbox div (dialog)
$('.editbutt').click(function() {
editRow = $(this).parents('tr').index();
//alert(editRow);
var fn = $(this).parents('tr').find('td').eq(0).find('.fname').val();
var ln = $(this).parents('tr').find('td').eq(1).find('.lname').val();
var em = $(this).parents('tr').find('td').eq(2).find('.email').val();
$('#mfn').val(fn);
$('#mln').val(ln);
$('#mem').val(em);
$('#msgbox').dialog('open');
}); //END editbutt
$('#alert').dialog({
autoOpen:false,
modal:true
});
}); //END document.ready
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
First Name
</td>
<td>
Last Name
</td>
<td>
Email
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" id="fn1">
</td>
<td>
<input type="text" class="lname" id="ln1">
</td>
<td>
<input type="text" class="email" id="em1">
</td>
<td>
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
<tr id="tr2">
<td id="td2a">
<input type="text" class="fname" id="fn2">
</td>
<td id="td2b">
<input type="text" class="lname" id="ln2">
</td>
<td id="td2c">
<input type="text" class="email" id="em2">
</td>
<td id="td2d">
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
</table>
<div id="msgbox">
<h2>Edit User</h2>
First Name: <input id="mfn" type="text"><br/>
Last Name : <input id="mln" type="text"><br/>
Email Addy: <input id="mem" type="text"><br/>
</div>
<div id="alert"></div>
</body>
</html>
PHP Processor File: my_php_processor_file.php
<?php
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$em = $_POST['email_addy'];
$uid = $_POST['user_id'];
/*
//This is where you use the security features of PHP to strip_slashes, and
//protect html_entities, etc. to guard your database against SQL injection
//attacks, etc. SEE THESE POSTS:
http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx
*/
//Now, update the database:
$success = mysql_query("UPDATE `users` SET `email`='$em', `first`='$fn', `last`='$ln' WHERE `user_id` = '$uid'");
//Now, return a message or something
if (mysql_affected_rows() == -1) {
$output = '<h2>Sorry, database update failed</h2>';
}else{
$output = '<h2>Update successful</h2>';
}
echo $output;

Adding array of textbox using javascript into html

Is something wrong with my code?
<script>
function add(){
/* Get your form */
form = document.getElementById("test");
/* Create your input element */
input = document.createElement("input");
input.type="text";
input.name="array['artists']";
/* Append to form */
form.appendChild(input);
alert("done");
}
</script>
<table>
<tr>
<td align="right">Artist/s:</td>
<td><form id="test" enctype="multipart/data-form" method="post">
<input type="text" name="artists"/>
<input type="button" onclick='javascript: add()'/></form></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
Im trying to add another textbox below another but nothing happened. What should i do?
Seems to be working for me too.
When I first put it into an html file, Internet Explorer wouldn't let me run the javascript because the html file was local to my computer. Try another browser if that's what you're using. Or just click yest to allow it in IE if that's the case.
Seems to be working - fiddle
I just put a call to add() inside a setTimeout so it would execute a second after the page loads.
Are you just missing the call to add()?
edit: I didnt originally see the onclick bound. new working fiddle2
Works for me as well. Try testing in another browser..
Your HTML-formatting is not right. This is why the input-box (TextBox) is added after the 'add'-button and not underneath it as you would like.
You can try the following code:
var table = document.getElementById("tableAddRows");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td2.appendChild(input);
row.appendChild(td1);
row.appendChild(td2);
table.appendChild(row);
Add an id to the table (in the sample "tableAddRows").
Also, I added the Submit-button in a different table, like so (there are neater solutions):
<table>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
Also place the form-element around both tables.
I would also suggest to use JSRender or jQuery Templates to achieve your purpose.
Here's the sample code, if your still trying to figure it out.

Javascript PHP a pop up image appear when click on search, after close image display search results

I want to do a 'pop up image' using javascript to display a simple user guide image, after the user click on search the image will pop up, to give them a better understanding of the results. So when the user close the image they will be link to results.php. Sorry that I can't provide any useful javascript codes, because those codes that I've found from the internet is too long. And I'm very noob at javascript.
Save Post->Session
<?php
$loan_amt = $_POST['loan_amt'];
if($_POST['search']){
if($_POST['loan_amt']=="" || $_POST['loan_tenure']==""){
$error = "Please fill up the mandatory fields";
}else{
session_start();
$_SESSION['property_type'] = $_POST['property_type'];
$_SESSION['property_status'] = $_POST['property_status'];
$_SESSION['loan_amt'] = $_POST['loan_amt'];
$_SESSION['loan_tenure'] = $_POST['loan_tenure'];
header("location:rates_result.php");
}
}
?>
Search Form (loan amount field)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="this.loan_amt.value=this.loan_amt.value.replace(/\,/g,'')">
<table width="400px">
<tr>
<td class="color1" width="130">Loan Amt (SGD)*:</td>
<td width="258" align="left">
<input type="text" style="width:150px;font-size:16px" onkeyup="format(this)" onchange="format(this)"
onblur="if(this.value.indexOf('.')==-1)this.value=this.value" name="loan_amt">
</td>
<td width="258" align="left"><input type="submit" class="buttonStyle" name="search" value="search" /></td>
</tr>
</table>
</form>
in the popup page you can put in section:
<script type="text/javascript">
window.onclose=goToResults
function goToResults(){
//do the parent go to results.php
parent.location="results.php";
}
</script>
if its a form to be submitted you can point a function on parent and that function can submit the form:
in popup:
function goToResults(){
//do the parent go to results.php
parent.submitForm();
}
in page:
function sumbitForm(){
form_to_submit=document.getElementById("FORM_ID");
form_to_submit.submit();
}

subtraction using javascript

The below coding is my doubt. the total fees value is fetched from db. and paid is currently we enter. now i want that if i enter any value in paid, the entered value is subtract from db value and new value is display in bal fees text box and as well as store in db.
my coding is...
<HTML>
<HEAD>
<script language="javascript">
function doMath()
{
var oldbal= parseInt(document.getElementById('totalfees').value);
var paid= parseInt(document.getElementById('paid').value);
var totalfees = oldbal-paid;
document.getElementById('totalfees').value = totalfees;
}
</script>
</HEAD>
<body>
<?php
//fteching query
include("db.php");
$billtype_id = $_GET['billtype_id'];
$result=mysql_query("select * from bill_type where billtype_id=$billtype_id");
while($res=mysql_fetch_array($result))
{
$totalfees=$res['totalfees'];
}
//inserting query
$sql=mysql_query("insert into fees_admin values totalfees='$balfees' WHERE billtype_id='$billtype_id'",$conn);
include("config.php");
$balfees=$_POST['totalfees'];
$sql=mysql_query("insert into fees_admin values totalfees='$balfees' WHERE billtype_id='$billtype_id'",$conn);
?>
//html form
<form name="form" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<table>
<tr>
<td>Total Fees :</td>
<td><input name="total" type="text" id="oldbal" value="<?php echo $totalfees;?>" readonly="true" style="background-color:#FFFFFF"></td>
</tr>
<tr>
<td>Paid :</td>
<td><input type="text" id="paid" name="paid" onKeyUp="doMath();"></td>
</tr>
<tr>
<td>Bal Fees</td>
<td><input name="totalfees" type="text" id="totalfees" readonly="true" style="background-color:#FFFFFF"></td>
</tr>
</table>
</form>
Thanks for reading. please clear my doubt..
To be clear, input elements will return a string when you call "value". So in your example you would need to change the subtraction equation to:
var totalfees = parseFloat(oldbal) - parseFloat(paid);
You can use parseFloat to create a float from a string or parseInt if you don't need decimal precision.
You should probably also change you HTML code to make the DOM level 0 event "change" rather than keyUp. Its more consistent across a range of different browsers (Desktop, Mobile, Tablet).
Change
var oldbal= parseInt(document.getElementById('totalfees').value);
to
var oldbal = parseInt(document.getElementById('oldbal').value);
Function should then look like
function doMath()
{
var oldbal = document.getElementById('oldbal').value;
var paid = document.getElementById('paid').value;
var totalfees = parseInt(oldbal) - parseInt(paid);
document.getElementById('totalfees').value = totalfees;
}
I believe you were retrieving the wrong input element.

Retrieve data from mysql and update them accordingly

I want to retrieve data from my MySQL database and display it as a table (I don't mind any style, but preferred as a table). Then the data should display with a radio button or a normal button which update that specific row and changing a single column in that row to Active (Status making Active).
I have started it, but I still have issues with adding a radio button or a button. Then I thought of displaying the information in a table which inside a form. This form will have each radio buttons, when the person select that radio button and press submit. The data should be updated in the MySQL database.
Can someone guide me about this? I'm a bit confused. I'm confused because I have to add a form and in that form I have to add a table and all this stuff should be in a php file.
on formpost.php page you can do something like this for handling the list array you received from the previous page:
<?
$list = $_POST['list'];
foreach ($list as $key => $list_php)
{
$query1 = "SELECT * FROM `stu_entry` WHERE `stu_entry`.`Student_No` = '$list_php' AND `stu_entry`.`Out_Time` = '0000-00-00 00:00:00'";
$result1 = mysql_query($query1);
$row1=mysql_fetch_array($result1);
//whatever you want to do
}
?>
I forgot to tell you something in the previous post. In the form page, lets say you have 100 rows with 100 checkboxes. It would be nasty to manually check or uncheck all of them. As an alternative you could append a little script at the end of the page to handle the checking/ unchecking process for you:
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function countChecks(form){
var t=0;
var c=form['list[]'];
for(var i=0;i<c.length;i++){
c[i].checked?t++:null;
}
return t;
}
</script>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.formpost['list[]'])">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.formpost['list[]'])">
<i>with selected: </i>
<select name="submit_mult" id="submit_mult">
<option value="todo1">Action 1 </option>
<option value="todo2">Action 2 </option>
</select>
<input type="button" name="go" value="Go" onClick='if(countChecks(this.form)>0) {if(confirm("are you sure you want to \""+document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].text+" "+countChecks(this.form)+" items selected"+"\"")) {document.getElementById("referenceToSomeHiddenElement").value=document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].value;document.getElementById("formpost").submit();}} else alert("you have not selected any item!!")' >
Tell me if you need more help on this.
I first specify a MySQL command which in return gives me an array. I use a while statement to do something to each item in the array. The array is populated with the field name and the field contents.
$mysql = mysql_query("SELECT * FROM table");
while ($array = mysql_fetch_array($mysql))
{
$output .= '<form>Row: ' . $array['fieldname'] . ' <input type="button" value="Update" /></form>';
}
This extracts all rows from the table and adds a form to the variable $output for every result. I'm unsure of how you want to update your database, so you will have to look into it. You can use GET and POST methods.
Go ahead and try something like this. And tell me if that worked:
<p><b>your page name</b></p>
<form name="formpost" id="formpost" action="formpost.php" method="POST">
<table border="2" cellpadding="5" cellspacing="1" style="border-collapse: collapse" bordercolor="#999999" width="800">
<tr>
<td><b>Sno.</b></td>
<td><b>Field name1</b></td>
<td><b>Field name2</b></td>
<td><b>Field name3</b></td>
<td><b>Field name4</b></td>
<td><b>Field name5</b></td>
<td><b>Field name6</b></td>
<td><b>Field name7</b></td>
</tr>
<?
$sorting="";
if($orderby!="" && $direction!="") $sorting=" ORDER BY $orderby $direction";
$query = "SELECT * FROM table WHERE something = 'something' $sorting";
$result = mysql_query($query);
?>
<tr>
<?
$i=0;
while ($row = mysql_fetch_array($result))
{
$i++;
?>
<td><input type="checkbox" name="list[<?echo $i?>]" id="list[]" value="<?echo $row['some_primary_field_id']?>"><?echo $i?></td>
<td><?echo $row['Field1']?></td>
<td><?echo $row['Field2']?></td>
<td><?echo $row['Field3']?></td>
<td><?echo $row['Field4']?></td>
<td><?echo $row['Field5']?></td>
<td><?echo $row['Field6']?></td>
<td><p align="center">
<?
echo "<input title='button' name='change this row' value='Some Button' type='button' onClick=\"if(confirm('Press OK to change status to confirm')) {document.getElementById('someid').value='".$row['Field1']."';document.getElementById('formpost').submit();}\"/>";
?>
</td>
</tr>
<input type='hidden' name="hiddenlist[<?echo $i?>]" id="hiddenlist[]" value="<?echo "some boundry condition ".$row['Field2']?>">
<?
} //end of while
?>
</table>
</form>

Categories