how to collect radio button value during pagination? - php

I've been working on a small project lately that involves question and answer. So basically it's a quiz/test, whatever you call this page. I made a database as per requirement for all the questions and answers storage. So yea, the output is coming from a database. Now, I need to output 5 questions at a time in a page so used pagination to do it.
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$question = $row['questions'];
$opta = $row['optA'];
$optb = $row['optB'];
$optc = $row['optC'];
$optd = $row['optD'];
$id = $row['ctrlNo'];
$outputList .="
<p>$id. $question</p>
<div>
<input type='radio' name='question-$id-' id='question-$id-answers-A' value='A' />
<label for='question-$id-answers-A'>A) $opta </label>
</div>
<div>
<input type='radio' name='question-$id-' id='question-$id-answers-B' value='B' />
<label for='question-$id-answers-B'>B) $optb </label>
</div>
<div>
<input type='radio' name='question-$id-' id='question-$id-answers-C' value='C' />
<label for='question-$id-answers-C'>C) $optc </label>
</div>
<div>
<input type='radio' name='question-$id-' id='question-$id-answers-D' value='D' />
<label for='question-$id-answers-D'>D) $optd </label>
</div>
";
}
Okay, so I have 4 radio buttons for the choices of each question and they are all working perfectly. What I can't figure out is collecting their values during pagination. I mean, when I'm on page 1 and submit my answers it's working, but when I go to page 2 and submit my answers it doesn't pass the values collected from page 1. Now I'm running out of ideas how to do it. Can anyone guide me as to what I can possibly do to gather all the values of the selected radio button first from page 1 to the current page of the user and pass it to my php page, which verifies the answers? Here's the code in my html.
<form id="form1" name="form1" action="testpage5.php" method="POST" >
<?php print "$outputList"; ?>
<p><div style="margin-left:58px; margin-right:58px; padding:6px; background- color:#FFF; ">
<?php echo $paginationDisplay; ?>
</div></p>
<input type="submit" value="Submit Quiz"></input>
</form>`
testpage5.php is the page where I verify the answers comparing value of $_POST to the correct answer from the database. I used $_POST to collect the values of the radio buttons.

Have a look at $_SESSION. It's a super global array which stores values of a browser session.
An alternative is creating hidden form elements which contain the values of the previously submitted pages.

Related

Why are the nested forms processed with $_SERVER['PHP_SELF'] (same html file) not displaying/processing correctly?

I'm trying to get user input in a progressive sequence that leads to that input being sent by email. Sending by email is a whole other issue that I haven't tackled yet so not really worried about that.
The part I am having difficulty with is once the user gets to the "Send Email?" (Yes/No) radio buttons, the input from that question is not processed correctly.
I've gotten further with this by using a separate php file as the form action but still get errors related to emailName, emailAddress, and emailMsg not existing ("Notice: Undefined index...").
Furthermore, I still need to be able to use the $_POST[athletes] array further down but I'm guessing it's outside of the variable scope at that point.
So to bring that all together, I'm really asking a few questions:
1) How can I get all of the forms to work together in the same file?
2) When the program actually goes past the "Send Email?" radio buttons when I use a separate php file as the form action, why am I getting undefined index errors?
3) Why do I get an error when I try to use the athletes[] array further down in the code? Should I somehow be passing the array values to that part of the code?
The exact steps the user would take to get to the issue is:
Select 1 or more athlete checkboxes and click the 'Display Selection(s)' button.
Select 'Yes' for "Send Email?" and click the 'Submit' button.
Restarts the code for some reason.
Any help would be greatly appreciated. Also, this is my first post so sorry if I asked the question incorrectly or not according to site etiquette.
I also apologize for the long code fragment but I'm not sure what parts might be causing this to be incorrect.
<b><h1><center>Athelete Selection Screen</center></h1></b>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Athletes Available: </legend>
<input type="checkbox" id="student1"
name="athletes[]" value="Student1 Test">
<label for="student1">Student1 Test</label><br/>
<font color="grey">Football - Running back</font><br/>
<p>
<input type="checkbox" id="student2"
name="athletes[]" value="Student2 Test">
<label for="student1">Student2 Test</label><br/>
<font color="grey">Soccer - Left Forward</font><br/>
</p>
<p>
<input type="checkbox" id="student3"
name="athletes[]" value="Student3 Test">
<label for="student1">Student3 Test</label><br/>
<font color="grey">Baseball - Pitcher/Left Outfield</font><br/>
</p>
</fieldset>
<p>
<?php echo("\t\t\t\t\t"); ?><button type="submit" name="submit" value="submit">Display Selection(s)</button>
</p>
</form>
<fieldset>
<legend>Athletes You Selected: </legend>
<?php
if (!empty($_POST['athletes']))
{
echo "<ul>";
foreach($_POST['athletes'] as $value)
{
echo "<li>$value</li>";
}
echo "</ul>";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Send Email? </legend>
<input type="radio" id="Yes"
name="radioSendMsg[]" value="Yes">
<label for="student1">Yes</label>
<p>
<input type="radio" id="No"
name="radioSendMsg[]" value="No">
<label for="student1">No</label><br/>
</p>
<button type="submit" name="submitRadio" value="submit">Submit</button>
</p>
</form>
<?php
if (!empty($_POST['radioSendMsg']))
{
foreach($_POST['radioSendMsg'] as $radioMsg)
{
if($radioMsg == "Yes")
{
echo "\tPlease enter information regarding the email to be sent: ";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<label for="emailName"> Name: </label><br/>
<input type="text" size="25" id="emailName" name="emailName" />
</p>
<p>
<label for="emailAddress">E-mail Address: </label></br>
<input type="text" size="25" id="emailAddress" name="emailAddress" />
</p>
<p>
<textarea id="emailMsg" name="emailMsg" cols="30" rows="5"></textarea>
</p>
<button type="submit" name="emailSubmit" value="send">Send Message</button>
</form>
<?php
$msg = "Name: ".$_POST['emailName']."\n";
$msg.= "E-Mail: ".$_POST['emailAddress']."\n";
$msg.= "Message: ".$_POST['emailMsg']."\n";
$msg.= "<ul>";
foreach($_POST['athletes'] as $value)
{
$msg.= "<li>$value</li>\n";
}
$msg.= "</ul>";
$emailRecipient = "sjzerbib#gmail.com";
$emailSubject = "Athlete Selection Submission";
$emailHeaders = "From: Sebastien\n"."Reply-To: ".$_POST['emailAddress'];
mail($emailRecipient,$emailSubject,$msg,$emailHeaders);
echo "Message sent: \n".$msg;
}
else
{
?> <p /> <?php
echo "\n\nNo email will be sent for your last athlete selection.";
?>
<br/>Please click here
to return to the Athlete selection screen.
<?php
}
}
}
}
When you submit a form, only those controls contained within that form are included. The exception is successful controls that have the form attribute set to the id value of the form that was submitted.
So, given you had something like:
<form id="form-1" method="post">
<input type="text" name="first-input" />
</form>
<input type="text" name="second-input" />
The only value to be submitted would be that of first-input. If you add the form attribute to second-input:
<input type="text" name="second-input" form="form-1" />
Then the submission of the form would include both values. Unfortunately, the form attribute is not fully supported (IE and Edge have no support).
Of course, your markup is invalid, so that's a moot point. For starters, you cannot nest a form within a form. How a browser responds to markup that violates that rule is up to it's vendor, but in my experience is somewhat unpredictable. You're also using deprecated tags (<font> and <center> are no longer valid) and nesting elements incorrectly (<h1> is a block level element, whereas <b> is inline).
If you're doing a full submit each time (so the page gets submitted to itself and then reloads), then just use some sort of conditional to only render the dependent controls if the preceding form submissions were successful:
<?php
$canDoNextStep = !empty($_POST['input-1']);
?>
<form id="form-1" method="post">
<input type="text" name="first-input" />
<?php if(canDoNextStep): ?>
<input type="text" name="second-input" />
<?php endif; ?>
</form>
Lastly, whitespace is (mostly) ignored when your browser parses and displays your HTML, so you can lose the \t and \n values in your strings, unless you're concerned about how your markup looks if someone chooses to view source when using your form.

get submitted values with PHP DOM

I want to get the values that belong to the answers of a test.
There could be any number of questions.
A question has the HTML:
<form method='post' action='calificar.php'>
<div class='pruebaAlumno'>
<h5>Pregunta 3</h5>
<h3>¿Que factores definen la capacidad de una persona?</h3>
<input type='checkbox' name='respuestaAlumno[]'
value='Voluntad'> Voluntad <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Cultura'> Cultura <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Hábitos'> Hábitos <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Habilidad'> Habilidad <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Perfil'> Perfil <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Dones'> Dones <br>
<input type='hidden' name='idPregunta' value='41'>
<input type='hidden' name='tipo' value='C'>
</fieldset>
</div> <div class='calificar'>
<input type='submit' name='calificar' value='enviar' >
</div>
</form>
I want to get
Answer (respuestaAlumno)
questionID (idPregunta)
type (tipo)
from each question.
Then I want to save the data in an array.
A test can have as many questions as the teacher wants. The form has one submit button.
I´ve tried to get the data in different ways. Using JS DOM. Using POST.
I´ve found some PHP DOM tutorials but them all teach how to modify an static HTML.
Please help me to get the submitted data from each fieldset.
Thanks in advance.
You could format your form names like this.
First question
name="respuestaAlumno[0][]"
name="respuestaAlumno[0][]"
...
name="idPregunta[0]"
name="tipo[0]"
Second question
name="respuestaAlumno[1][]"
name="respuestaAlumno[1][]"
...
name="idPregunta[1]"
name="tipo[1]"
You would end up with three arrays in your $_POST.
Try this
<?php
if(isset($_POST['calificar'])
{
$respuestaAlumno=$_POST['respuestaAlumno'];
//you need respuestaAlumno array to single string
echo $data_to_string=implode(",",$respuestaAlumno);
$count_of_respuestaAlumno=count($_POST['respuestaAlumno']);
for($i=0;$i<=$count_of_respuestaAlumno-1;$i++)
{
echo $data=$respuestaAlumno[$i]."/n";
}
//question id
echo $idPregunta=$_POST['idPregunta'];
echo $tipo=$_POST['tipo'];
//do something
}

form submits url parameter instead of update

This is probably a really stupid question, but I can't figure out why my code is doing this. I'm trying to do a simple recordset update and yet when I hit the submit button on the page, it will reload the page and in the url have multiple url parameters of the info from the form.
I have two forms in the whole document, one, the one I'm working with is supposed to change a variable in the database to the username of the user
<form action="<?php echo $editFormAction; ?>" method="POST" name="Catch">
<input name="Horseid" type="hidden" value="<?php echo $colname_WildHorse?>"/>
<input name="Owner" type="hidden" value="<?php echo $colname_HorseImage?>"/>
<input name="Catch" type="submit" value="Catch"/>
<input type="hidden" name="MM_update" value="Catch"/>
</form>
This is the one that returns all the url stuff after I hit the submit button. The second form is under it, and I want that one to display in the Url, which it does perfectly fine. Why is this one freaking out though?
URL produced:
http://localhost:8888/TheMeadow.php?Horseid=38&Owner=redlilac78&Catch=Catch&MM_update=Catch
This is the result code: I left out the style sheet since it's a lot
<title>The Meadow</title>
<style type="text/css">
//Left out style
</style>
</head>
<body>
<div id="Background">
<div id="Logo"><img src="Images/RR_Art/Website pages/Logo/Ropin' Ranch logo.gif" width="229" height="192" /></div>
<div id="Map">Map</div>
<div id="Directories">Directories</div>
<div id="LogOut">Log out</div>
<div id="Note">
<form action="" method="get">
<p>
Welcome to the wild, where you can catch and search for wild horses! You can only catch one horse every two days so choose your horse wisely! </p>
<div id="Name"><br> <br> <br> <br> <br>
<form name = "WildHorse" id = "WildHorse" onSubmit="TheMeadow.php?HorseId43">
<input type = "hidden" name = "HorseId" value = "43"/>
<input type = "submit" name = "" value = "Search" />
</form>
</div>
</div>
</body>
In your form action the problem is with $editFormAction in php , it is either empty or having the same files name due to which the form is being submitted to the same page.

Pass Value of clicked button from one page to another page Input field

Weird question this, going round in circles.
I have 2 pages.
Page 1. Has a button on it. Like
<form action="goto_page_2.php"><p class="longdesc"><span class="spanBold">Scrap Collections in North Lakes:</span><br />
<button class="readViewMoreBtn" value="North Lakes">Book a Collection in North Lakes</button>
</p></form>
The above is a simple mockup. But what I want to do is, onclick of the button, parse the Value to ...
Page 2. Which has a form built in.
One of the fields is Suburb.
<!-- EMAIL SUBURB -->
<span class="commonControlLabel">Suburb:</span>
<span class="commonControlLabelItalic">(required)</span>
<span id="contactSuburbErrorMsg" class="commonControlErrorMsg"></span><br />
<input class="commonInput" type="text" id="inputSuburb" value=""/><br />
So what I want to do, is grab the VALUE of the button on PAGE 1, and add it to the Value in the input element on Page 2.
To complicate matters, Page 1. Has quite a few buttons, with different values, all unique, which we would like to pass, to the input element. Obviously onlcick of the button on page 1 we go direct to page 2.
Have the button post it's value to Page2:
Page1, I added type="submit" and name="suburb"
<button type="submit" name="suburb" class="readViewMoreBtn" value="North Lakes">Book a Collection in North Lakes</button>
Page2: I added the php part in the value attribute
<input class="commonInput" type="text" id="inputSuburb" value="<?= $_POST['suburb'] ?>"/>
<!--page1::-->
<html>
<body>
<form action="test2.php" method="post">
<button name="desc" value="1">description!</button>
</form>
</body>
</html>
<!--page2::-->
<?php
echo "hello";
echo $_POST["desc"];
?>
There are several things you can do.
E.g: on form 2 say:
<input type="text" value="<?php if(isset($_POST['inputNameForm1'])){echo htmlentities($_POST['inputNameForm1']);} ?>
Or if that is not an option for you, try something like:
<? php
session_start();
$_SESSION['sessionName'] = $_POST['inputNameForm1']?>
<input type="text" value="<?php if(isset($_SESSION['sessionName']])){echo htmlentities($_SESSION['sessionName']]);} ?> />
Note: didn't test the code

Form submitting but I don't know how or why?

I've made a normal HTML form which when submitted, sends information to another page and that page processes the data and adds it to the database. But for some reason, if I refresh the 1st page which contains the form, an entry is being made into the database even though I can't see any reason for it to do so.
This is the code for the form:
<?php $owner = $_GET['user']; ?>
<h2 class="dotted"><?php _e('Add feedback for user','appthemes'); echo " - ".$owner;?></h2>
<form id='feedback' action='http://www.example.co.uk/add-feedback-response/?user=<?php echo $owner; ?>' method='POST' accept-charset='UTF-8'>
<fieldset >
<b>Your Username:</b> <?php echo $current_user->user_login; ?><br/><br/>
<b>Rating: </b>
<input type="radio" name="rating" value="positive" /> Positive
<input type="radio" name="rating" value="neutral" /> Neutral
<input type="radio" name="rating" value="negative" /> Negative<br/><br/>
<label for='item' ><b>Item bought:</b></label>
<input type="text" name='item' id='item' maxlength="500"/><br/><br/>
<label for='comment' ><b>Comment:</b></label>
<textarea name='comment' id='comment' maxlength="2500"></textarea><br/><br/>
<input type="submit" id="submit-button" value="Submit Feedback" />
</fieldset>
</form>
Is there something I'm missing? Thanks for any help
It is probably because you're trying to submit form again. Is browser alerting you that you're sending data again?
to restrict this, use
header("Location: ".$_SERVER['HTTP_REFERER']);
in proccessing form
If you refresh the form after it has submitted once, the form will be submitted again. (the browser would have warned you, "Are you sure you want to submit the page again" - didn't it?) Refresh is actually "repeat the last request".
If you think such a scenario is possible in your webapp, you will have to handle duplicate requests.

Categories