I have a form where the user clicks various radio groups, this generates a 'score' that is calculated with javascript, and populates a textbox at the top of the form with a running total.
When the form is submitted, the POST value for this textbox is empty, so when it moves onto the output sheet there is no value to display.
All other textboxes that are manually typed in work fine. All Names/Ids etc are correct, is there something I'm missing in order to get it to correctly retain the value generated by the JS in the POST value when the form is submitted?
This (populated from JS) doesn't work :
<input name="Result_AutoFail" type="text" class="ResultsBox" id="Result_AutoFail" size="2" maxlength="2" value="<?php echo htmlspecialchars($_POST['Result_AutoFail']); ?>"/>
but this (Manually typed in) does:
<input name="CustName" type="text" id="CustName" size="25" maxlength="25" value="<?php echo htmlspecialchars($_POST['CustName']); ?>"/>
The JS used to populate the box is this for each question, this works fine and puts the value into the box correctly as the user clicks each radio button for each question, just doesn't send it off to POST:
for (i=0;i<2;i++)
{
if (document.MonitorForm.SBI_CA027[i].checked == true)
{
CA027Selected = document.MonitorForm.SBI_CA027[i].value
}
}
if (CA027Selected == "Yes")
{
if (AutoFailCount == 0)
{
document.MonitorForm.Result_AutoFail.style.backgroundColor = "#008000";
}
else if (AutoFailCount >= 1)
{
document.MonitorForm.Result_AutoFail.style.backgroundColor = "#FF0000";
}
}
else if( CA027Selected == "No")
{
AutoFailCount = (AutoFailCount + 1);
if (AutoFailCount == 0)
{
document.MonitorForm.Result_AutoFail.style.backgroundColor = "#008000";
}
else if (AutoFailCount >= 1)
{
document.MonitorForm.Result_AutoFail.style.backgroundColor = "#FF0000";
}
}
Then is written into the textbox with:
document.MonitorForm.Result_AutoFail.value = AutoFailCount ;
Cheers!
Try writing the result into hidden input.
<input type="hidden" value="some_value" name="result" id="result" />
if you dont submit it from a formfield like input or textfield it wont come in the $_POST array
if you want to submit additional data in your post you have to write them in hidden inputs
Related
I have a form of different types of input fields. It looks something like this:
<form action="function.php" method="POST" ...>
<select name="table" ...>
<option> ... </option>
<option> ... </option
</select>
<select name="column" ...>
<option> ... </option>
<option> ... </option
</select>
<input type="text" name="searchword">
<input type="button" name="operator" value="=" id="operator" onclick="change(this.id)">
<input type="submit" ...>
</form>
With my dynamic button, I can switch the operators (=, <, >) with my "change()" function which I need to create my queries. In my function.php file, I'm trying to get all the values of my input fields ...
$table = $_POST["table"];
$column = $_POST["column"];
$operator = $_POST["operator"];
... but unfortunately, it only works for the table and for the column input. I can't store the value of my operator button. I tried to find a solution for my problem but most people wrote that I have to change my button's input type to "submit" to pass the value. However, I do not want the action to be executed directly when this button is pressed, but only when the real "submit" button is pressed.
Edit:
Here is my "change()" function:
function change(operatorId) {
let element = document.getElementById(operatorId);
if (element.value == "=") {
element.value = ">";
} else if (element.value == ">") {
element.value = "<";
} else if (element.value == "<") {
element.value = "=";
}
}
And this is the error message I get when the function.php file opens: "Undefined array key "operator" in ..."
Edit: Solution
Thanks to Professor Abronsius' answer, I was able to resolve my problem. As he suggested, I inserted another hidden input field with the name "operator" and changed my button to "operator-selector". In this way, I just had to add some lines to my function to change the hidden field's value. This is how it looks like now:
<input type="hidden" name="operator" id="operator" value="">
<input type="button" name="select-operator" value="=" id="select-operator" onclick="change(this.id)">
function change(selectorOperatorId) {
let selector = document.getElementById(selectorOperatorId);
if (selector.value == "=") {
selector.value = ">";
document.getElementById("operator").value = selector.value;
} else if (selector.value == ">") {
selector.value = "<";
document.getElementById("operator").value = selector.value;
} else if (selector.value == "<") {
selector.value = "=";
document.getElementById("operator").value = selector.value;
}
}
What you could possibly do would be to keep the button as a regular button but change it's name and then add a hidden input named operator - the value can be assigned by the change function and will appear in the POST array.
Incidentally I had already written the alternative change function below before I saw the edited question. It does have the advantage of being easily extensible if other operators were required/possible.
If the button were changed to a submit the change function would need to have the event passed in as an argument and then call event.preventDefault(); to stop the form from actually being submitted.
const change=function(e){
e.preventDefault();//if the button was a `submit` button this would stop the form being submitted.
const operators=['=','>','<'];
const input=this.parentNode.operator;
let i=Number( this.dataset.i );
let j=i < operators.length-1 ? i+1 : 0;
this.dataset.i=j;
input.value=this.value=operators[j]
}
document.querySelector('input[type="button"][name="op-selector"]').addEventListener('click',change);
<form method='POST'>
<select name='table'>
<option>coffee
<option>dining
</select>
<select name='column'>
<option>doric
<option>corinthian
</select>
<input type='text' name='searchword' />
<input type='hidden' name='operator' />
<!--
the button appears the same but now sets the value of the real `operator`
field.
-->
<input type='button' name='op-selector' data-i=0 value='=' />
<input type='submit' />
</form>
Change input type from button to submit and then you can access button value with $_POST["operator"];
<input type="submit" name="operator" value="=" id="operator" onclick="change(this.id)">
If you're using a style framework and don't want your button type to get affected add another hidden field with text type and change its value programmatically.
value
Defines the value associated with the button’s name when it’s submitted with the form data. This value is passed to the server in params when the form is submitted using this button.
As documented here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
I have a submit button in my form which when clicked, the text in my text field disappears. I basically need the text to stay because I have another button that requires the text in that text field. The two buttons are parts of two different functions and I was wondering if there was a way to use the value of the variable in the function of one button in the function of the other.
For example, here is the code for one of the buttons:
Enter customer name<input type="text" name="cname">
<input type="submit" name="sub" value="Display">
<?php
if(isset($_GET['sub'])){
display();
}
function display(){
include 'config.php';
$searchstr=$_GET['cname'];
echo "<input type='hidden' name='cname1' value=".$searchstr.">";
$td=$_GET['cname1'];
$sql="select * from info where cname='$searchstr';";
$result=mysqli_query($conn, $sql);
if($searchstr==""){
$message="Please enter a customer name";
echo "<script type='text/javascript'>alert('$message');
window.location.href='retreive.php';</script>";
}
else{
echo "<table id='info' border='1px solid black'><tr padding='2'><th>Customer Name</th><th>Purchase Order Date</th><th>Started?</th><th>Reason (If any)</th><th>Tentative start date</th><th>Progress</th><th>Current Status</th><th></tr>";
while ($row = $result->fetch_assoc()) {
$cname=$row['cname'];
$podate=$row['podate'];
$started=$row['started'];
$reason=$row['reason'];
$tentdate=$row['tentdate'];
$progress=$row['progress'];
$status=$row['status'];
echo "<tr><td>".$cname."</td><td>".$podate."</td><td>".$started."</td><td>".$reason."</td><td>".$tentdate."</td><td>".$progress."</td><td>".$status."</td></tr>";
}
echo "</table><br>";
}
Everything works perfectly here and displays the table as required. But notice the variable $td above. I need that value displayed when my other button is clicked, which is in a different function.
Here's the code for the other button:
echo "<input type='submit' name='fp' value='Finished payment'>";
if(isset($_GET['fp'])){
echo $td;
}
Clicking that button doesn't display anything which means I am not able to read this variable outside the display function.I have tried looking up global variables in php and another solution was to use the and then use Javascript but I want to use php and I need the text to remain in the text field after the submit button is clicked so that I can read it later.
Thank you.
Once you submit the form, the text entered by the user disappeared? It's the default behavior of the browser. To avoid this either submit form using jQuery or store the value of the input into variable and echo.
Sample code for Jquery:
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'application/json',
data: $("#myform").serialize(),
success: function(data) {
... do something with the data...
}
});
});
==If not using Jquery==
PHP:
$myValue = $_POST['my_input_name'];
HTML:
<input type="submit" name="sub" value="<?= $myValue ?>">
You can simply create a variable for the value, then place that variable in the value section of the other input.
$name= 'Enter Name';
if(isset($_GET['cname'])){
$name = $_GET['cname'];
}
Then
<input type="text" name="cname" value="<?=$name?>">
Using placeholder attribute:
<input type="text" placeholder="Enter Name" name="cname" value="<?php echo $name; ?>
Before the $_GET['cname'] has been processed, the value within the input field is set to the text you wish to show, or simply keep it empty. Then once the $_GET['cname'] has been posted, you check to see if it is set, then set the variable to equal the returned information the user entered in the other field - $td.
<?php
$cname = ''; // or $cname = 'Enter a Name';
if(isset($_GET['sub'])){
display();
}
function display(){
include 'config.php';
$searchstr=$_GET['cname'];
$td=$_GET['cname'];
$sql="select * from info where cname='$searchstr';";
$result=mysqli_query($conn, $sql);
if($searchstr==""){
$message="Please enter a customer name";
echo "<script type='text/javascript'>alert('$message');
window.location.href='retreive.php';</script>";
}
else{
//use isset to see if that has been posted
if(isset($_GET['cname'])){
$name = $_GET['cname'];
//$name is now set to the value you wish to display in the value of the other input
//call on the value like so <input type="text" name="cname" value="<?=$name?>">
}
echo "<table id='info' border='1px solid black'><tr padding='2'><th>Customer Name</th><th>Purchase Order Date</th><th>Started?</th><th>Reason (If any)</th><th>Tentative start date</th><th>Progress</th><th>Current Status</th><th></tr>";
while ($row = $result->fetch_assoc()) {
$cname=$row['cname'];
$podate=$row['podate'];
$started=$row['started'];
$reason=$row['reason'];
$tentdate=$row['tentdate'];
$progress=$row['progress'];
$status=$row['status'];
echo "<tr><td>".$cname."</td><td>".$podate."</td><td>".$started."</td><td>".$reason."</td><td>".$tentdate."</td><td>".$progress."</td><td>".$status."</td></tr>";
}
echo "</table><br>";
}
php fiddle: Good for 48 hours only - http://main.xfiddle.com/8f416cc9/input.php
I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>
I'm coding an HTML form where I've implemented an anti-spam system where two random numbers are generated and the user is asked to input the sum into a text field. If the answer is right, then the 'submit' button appears and the user can move on. If the answer is incorrect, then a notification saying, 'Incorrect answer'. The HTML form itself is in a table. In the very last row of cells I've put this code in:
<td>
<?php
$firstnumber = rand(0, 5);
$secondnumber = rand(0,6);
echo 'Anti-spam: '.$firstnumber.' + '.$secondnumber.' = ?</td><td><input name="human" placeholder = "Do the math">';
?>
</td>
<tr>
<td colspan="2">
By submitting this form you are agreeing to the terms of service and agreements.<br><br>
<?php
$answer = $_POST['human'];
if($answer == $firstnumber + $secondnumber) {
echo '<input id="submit" name="submit" type="submit" value="I Agree"> <input id="reset" name="reset" type="reset" value="Reset">'; }
else {
echo '<font color=#ea596c>Incorrect answer</font>';
?>
</td>
But the 'submit' button won't reappear when the answer is entered into the box :(
option 1 (not too secure) add hidden input with correct answer
<input type="hidden" name="answer" value="<?=$firstnumber+$secondnumber;?"/>
and check the data after submit
if($_POST["anwer"]==$_POST["human"]) ...
option 2 remember the correct answer with SESSION. If you want to do server side check, you must display submit button - the data must be sent to the server. To display/hide the submit button, you must do client side check and use javascript, see option 3.
<?
session_start(); // necessary to use session vars
$firstnumber = rand(0, 5);
$secondnumber = rand(0, 6);
if(!empty($_SESSION["answer"]) && $_SESSION["answer"]==#$_POST["human"]) {
// the math was ok
}
$_SESSION["answer"] = $firstnumber + $secondnumber; // must be AFTER the check
?>
<form method="post">
<?="$firstnumber + $secondnumber = ";?>
<input name="human" type="text" placeholder="do the math"/>
<input type="submit"/> <!-- can't be hidden without javascript -->
</form>
option 3 client side javascript solution, something like vasiljevski recommend
<span id="first"></span> + <span id="first"></span>
<input oninput="check(this)" placeholder="do the math"/>
<input type="submit" id="submit" style="display: none"/>
<script>
var first=Math.floor(Math.random()*10);
var second=Math.floor(Math.random()*10);
var gid = document.getElementById.bind(document);
gid("first").innerHTML = first;
gid("second").innerHTML = second;
function check(input) {
gid("submit").style.display = input.value==first+second ? "inline" : "none";
}
</script>
You would need to add some JavaScript to your form to achieve that.
Add a keypress event on input and check if entry is valid.
<input id="antispam" name="human" onkeyup="checkEntry" placeholder = "Do the math">';
?>
<script>
function checkEntry()
{
var x=document.getElementById("antispam");
if (x=={correct answare})
{
[add submite button]
}
else
{
[add incorrect text]
}
</script>
You are generating new random numbers on every page load. So when the user is doing the math and submitting the form, it happens a new request and your random numbers are generated new, so the calculation cannot match (randomly it could be the same result).
You have to store the math result in session or an hidden input field (encoded or something else) that you know the result after submitting the form.
Or you want to check the result in JavaScript to show the button, but I wouldn't do an humanity check on the client.
hi my code in html is like this
<input type="radio" name='answer_value1[<?php echo $survey1->id?>]' value="<?php echo $answer1->id?>" validate="required:true" id="<?php $answer1->valdt == '1' ? print "welcome":""?>" />
And this is code for comment box
<textarea rows="5" cols="55" name="nn[<?php echo $survey1->id?>]" id="comment" ></textarea>
if the radio button id is "welcome" then i want to make the textarea should be validate otherwise not.
and i wrote some code in jquery
$(function() {
$('input[id="welcome"]')).change(function() {
$('textarea[id="comment"]').each(function(){
$(this).rules("add", {
required: true,
} );
} );
If i click this field first and after if i clicked another radio button it's still validate this textarea field.
please give me some idea
FYI, ajax is not for validation. Its for asynchronous fetching of data from the server.
if (document.getElementById('welcome').checked) {
var textarea = document.getElementById('comment');
if (textarea.value = '') {
// validation failed
return false;
} else {
return true;
}
}
Did you try this :
var v = document.getElementById("validation1");
ValidatorValidate(v);
by this line of code you can force validator to check validation.
so you can add validation control for your textBox and run above code on radio button selectedChanged event handler.