Updating hidden input depending on what user has checked - php

I've created a test system that has multiple steps (using jquery) allowing users to check checkboxes to select their answers, with a summary page and a final submission button... all within a form. I now want to create the scoring system.
1) Firstly this is the code (within a loop) that grabs the answers from Wordpress for each question:
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo $row['answer']; ?>" />
2) In Wordpress next to each answer is a dropdown with a yes or no option to mark whether the answer is right or wrong. This is output in the following way:
<?php $row['correct']; ?>
3) Each correct answer the user checks should be worth 1 point. The passmark is determined by the field:
<?php the_field('pass_mark'); ?>
4) I want it to update a hidden field with the score as the user checks the correct answer:
<input type="hidden" value="<?php echo $score; ?>" name="test-score" />
How can I update the hidden field with the user score as the user is checking the correct answer? I'm not sure what to try with this to even give it a go first!
Ok, everyones spotted a big hole in this. I'm completely open to doing it a hidden way so people can't check out the source. The type of user this is targeted at wouldn't have a clue how to look at the source but might as well do it the right way to start with!
The whole test is within a form so could it only update the hidden field on submit?
I still need some examples of how to do it.

In my opinion you should use sessions for that purpose, because any browser output may be saved and viewed in ANY text editor. This is not right purpose oh hidden input elements. You use hidden inputs when you need to submit something automatically, but never use it when processing some important data.
Mapping your questions and answers via id will allow you not to reveal real answers and scores in HTML.
Just a very simple example how to do that:
<?php
$questions = array(
125 => array("text"=>"2x2?", "answer"=>"4", 'points'=>3),
145 => array("text"=>"5x6?", "answer"=>"30", 'points'=>2),
);
?>
<form method="post">
<?php foreach ($questions as $id => $question): ?>
<div><?php echo $question['text'] ; ?></div>
<input type="text" name="question<?php echo $id ; ?>"/>
<?php endforeach ; ?>
<input type="submit" value="Submit"/>
</form>
/* In submission script */
<?php
if (isset($_POST['submit'])){
foreach($questions as $id => $question){
if (isset($_POST["question{$id}"])){
$answer = $_POST["question{$id}"] ;
if ($answer === $question['answer']){
$_SESSION['score'] += $question['points'] ;
}
}
}
}

Spokey is right - the user would be able to cheat if your score it on the client side like using the method you suggested.
Instead, either user a JQuery $.post call to post each answer and then store the score in a PHP Session. Or just wait until the entire form is submitted and evaluate the score of the form as a whole on the server side.
* Update *
You have to submit the form to a script that can evaluate the form. So say it gets submitted to myForm.php
In myForm.php, get the post vars:
$correct_answers = $however_you_get_your_correct_answers();
//Assuming $correct_answers is a associative array with the same keys being used in post -
$results = array();
if($_POST){
foreach ($_POST as $key=>$value) {
if ($_POST[$key] == $correct_answers[$key]){
$results[$key] = 'correct';
}
else $results[$key] = 'incorrect';
}
}
This is untested, but it should work.

Related

How to pass array values of checkbox to next part in multi-part form

I have a site based on wordpress. I need to allow people to create posts from frontend so I have made a multi-part form which works pretty well. There are three parts of the form and each part of the form is validated before moving to the next part. Data is passed to another page through hidden inputs.
My form template looks somewhat like this ( complete code is pretty massive and irrelevant here, so just showing just the relevant parts ) which I hope is enough to give an idea how the form works.
MULTI-PART FORM WP-TEMPLATE SAMPLE CODE :
<?php
global $wpdb;
$this_page = $_SERVER['REQUEST_URI'];
$page = $_POST['page'];
if ( $page == NULL ) { ?>
<?php include_once('multiparts/form-files/first_part.php'); ?>
<?php } else if ( $page == 1 ) { ?>
<?php include_once('multiparts/validation/validate_first_part.php');
if (isset($_POST['submit-1']) && (!empty($error))) { ?>
<div class="error-head">Cannot continue registration. Error/s highlighted below.</div><br/>
<?php echo $error . '</br>'; ?>
<?php } else {
include_once('multiparts/form-files/second_part.php');
}
?>
<?php
} else if ( $page == 2 ) { ?>
//SO ON AND SO FORTH
<?php
}
?>
Recently, I have a added several checkbox fields in the form with an intention to display values of selected checkboxes, in the created posts. So here is a relevant html form code that I am currently using.
<fieldset class="work-areas">
<label for="areas" class="label">INTERESTED IN :</label></br>
<div class="work-class">
<input type="checkbox" name="workareas[]" value="administration"/>administration</br>
<input type="checkbox" name="workareas[]" value="technical"/>technical</br>
<input type="checkbox" name="workareas[]" value="creative"/>creative</br>
<input type="checkbox" name="workareas[]" value="fieldwork"/>fieldwork</br>
<input type="checkbox" name="workareas[]" value="marketing"/>marketing</br>
</div>
</fieldset>
I insert the values of these checkboxes into the post just like any other custom fields using this code: add_post_meta($pid, 'areas', $workareas, true );. In the processing part it is assigned a meta_key areas. I display it in the single.php with the code below :
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>
ISSUE: All this works well when the above given html form code for checkboxes is in the last/third part of the form. But it does work when the same checkbox fields is in the second part of the form. I guess it simply does not pass the array values of the selected checkboxes to the third part. Print_r shows an empty array and obviously does not display anything in the single.php too. Although I understand that the trouble is just the array of selected checkbox values, NOT being carried to the third part properly, I need help as I am noob to all this.
So the bottomline question is how do I save the array of the selected
checkboxes' values in the second part and carry it to the third part
and finally assign it to a variable which will hold the array values.
That which can be displayed in post using the code above.
THINGS TRIED : I have looked into this thread here and I am confused where I will insert my checkbox fields and not even sure it applies to my situation. I have been able to pass other text input values from one part to another part of the from using something like this :
<input type="hidden" name="eligible" value="<?php echo $eligible;?>" />
So, I tried using name="workareas[]" but did not work. I am doing print_r() for everything I am trying and till now have only been getting empty array. I am still going through tons of other threads looking for possible hints. In the meanwhile if you can help, that will be great. Thanks in advance.
UPDATE : Solved, please check the answer.
Not a WP user but your checkboxes are named "workareas" but you seem to refer to them as "areas" everywhere else.
Thanks for the suggestions in the comments but I have found a graceful and robust solution in my opinion, that is using sessions. I followed the basic idea from here which actually deals with a multipart form with sessions. Now I have the following code in my third/last part of the form, at the very beginning of the document. At this time please remember that the html checkbox fields as illustrated above in the question are in the second part.
<?php
session_start();
$_SESSION['workareas'] = $_POST['workareas'];
$result=$_POST['workareas'];
?>
The code is that is repeated during the validation of the third part is the same but this way the variable $result is still holding the values of the array of the selected checkboxes from the second part of the form.
session_start();
$result=$_SESSION['workareas'];
You can do a print_r($result) at this point and check. Furthermore, if you want to insert these array values to post in order for them to show up in the post just assign meta_key eg. areas to $result and use the code below to add it as a custom field :
add_post_meta($pid, 'areas', $result, true);
In the single.php you can use the code below to pull values from the array and show. Do not avoid if(is_array) statement else wordpress might throw an error warning: invalid arguments supplied foreach(). Goodluck.
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

How to get post values from first page to third page ,as post

i have 3 pages
Page1.php,page2.php,page3.php
In page1.php, i have some hidden values, for example 'name'
After the submission of page1.php, it will go to page2.
Then after some process in page2.php, it should need to automatically submit to page3.php(where page3.php is in another sever)
Finally,when i print the $_POST variables in page3.php, i need to get the variable 'name'
you could stick it in the session
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
or you could pass them in hidden vars on page2.php if it has a form...
You will want to look into sessions.
If you need them in POST, try this:
$display = "";
$saveFields = array('one', 'two'); // whitelist of fields to add to the form hidden
foreach ($_POST as $key => $val) {
if (!empty($val) && in_array($key, $saveFields))
$display .= '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}
echo $display;
Should get you where you want to go. The whitelist just ensure's that random stuff is not injected that does not need to be.
(1) Option is to add hidden input on page2 too.
(2) Option is to set the value from page1's name into session and use it on page3
There are several solutions:
PHP sessions
cookies
passing arguments as GET/POST parameters
storing data in database
In simple cases passing arguments as GET parameter page2.php?name=... or using hidden form field is the best solution
This seems straightforward to me, page one has a hidden value called name. Page 2 should retrieve the post $_POST['name'] and print it on page 2 as a hidden field. Once you post it to Page 3 you can retrieve it the same way $_POST['name'].
Realistically if the data is exactly the same and is being carried all the way to page 3, why do you even need it? Can you not just declare it on page 3?
Okay, the way I read this is that on your first page you have a UI with a form. The form is then submitted for processing to page 2. After processing is done, you want to redirect, if you will, the user to another site (or server, doesn't necessarily have to make a difference).
If I got that right, here is what you should do; instead of using the header(); function (php), print an empty page with a hidden form with all of the details you want to send over and use javascript to emulate the user 'submitting' the form.
< div style="display: none;">
< form action="https://mywebpage.com/myscript.php" method=POST>
< input type=hidden name="key_1" value="value_1">
< input type=hidden name="key_2" value="value_2">
< input type=hidden name="key_3" value="value_3">
< input type=submit id="formButton" style="visibility: hidden; ">
< script language="javascript">
document.getElementById("formButton").click()
< /form>
< /div>

PHP quiz send data to next page

ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.

Categories