Button Value Not Changing when Text Field Isn't Empty - php

Having a small issue getting my submit button to change the value when the php variable isn't empty. So the way I have it set up is that when the button "GO" is pressed it will set the value of the text field to "1234567890" meaning it is no longer empty. Now when the page first loads the text field will be empty and the button should say "GO" once pressed the text field value will change and the button should now say "REFRESH" however it stays saying "GO" can anyone see where I'm going wrong here?
Thanks.
PHP
<?
if (!$HostKey){
$HostBtn = 'GO';
}
else{
$HostBtn = 'REFRESH';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['Go'])) {
$HostKey = "123567890";
}
}
}
?>
HTML
<form action="Home.php" method="post">
<p><strong>HOST:</strong>
<input name="Host" id="Host" type="text" value="<? echo $HostKey; ?>" maxlength="10" disabled>
<input name="Go" id="Go" type="submit" value="<? echo $HostBtn; ?>"></p>
</form>

Your issue is a logical one, as $HostKey isn't defined prior to you doing your check - so $HostKey is null. You define it after that. Then, because the variable is effectively null, when you apply the not-operator !, that condition is always true.
You should refactor your code to check if the form was submitted, and define the value of the variable based on that instead. All you need in PHP would be
$HostBtn = isset($_POST['Go']) ? 'REFRESH' : 'GO';
$HostKey = isset($_POST['Go']) ? 123567890 : '';
This would also fix the "Undefined variable..." notices you should have been getting if you enabled error-reporting,
error_reporting(E_ALL);
ini_set("display_errors", 1);
Which should be enabled while in development. In a live environment, you shouldn't display the actual errors though - but its fine to do that under development.

You should try something like :
<?
if (isset($_POST['Go'])) {
$HostKey = "123567890";
$HostBtn= "REFRESH";
}else{
$HostKey="";
$HostBtn="GO";
}
?>

Related

Trying To Post Via Button

I Have tried many solutions posted on stack overflow and non of them have worked.
It could just be me but i tried it on a separate file and it worked but if i use my current site with nice css it won't work
I Have tried the exact code on LAEPHP and it worked but when i added my code as you can see below it does not display anything when the button is clicked and it does not even refresh the page on click
<form action="" method="post">
<div class="form-group">
<label>Username</label>
<input class="au-input au-input--full" type="email" name="target" placeholder="Example">
</div>
<div class="form-group">
<label>API key</label>
<input class="au-input au-input--full" type="text" name="key" placeholder="X7UI-9H2D-IZAS">
</div>
<?php
$key= $_POST['key'];
$send= $_POST['send'];
if ($send) {
if (!empty($key)) {
echo 'The key you entered is ' . $key;
}
else {
echo 'You did not enter a key. Please enter a key into this form field.';
}
}
?>
<button class="subscribe btn btn-primary btn-block" name="send" type="submit">Check Key</button>
</form>
The problem I see is that you're checking if the button was sent and isn't "falsy". Since you don't have a value-attribute on the button, it will be an empty string, which is a "falsy" value, meaning that the first if-statement will never evaluate as true.
Try changing your code to:
<?php
// isset() is better since it check if the key exists and isn't null.
if (isset($_POST['send'])) {
// If you rather put the values in separate variables,
// you should do it here, inside the if-statement (where we know we
// got a POST request)
if (!empty($_POST['key'])) {
echo 'The key you entered is ' . $_POST['key'];
}
else {
echo 'You did not enter a key. Please enter a key into this form field.';
}
}
?>
The variable $send is null when the form is being sent to the browser and an empty string (""") when the browser is posting the form. In PHP, when converted to a boolean (as in your if ($send) statement), both of these evaluate to false and the code inside the if statement doesn't run.
The quick fix would be to change it to:
if ($send !== null) // the `!==` is for preventing the type juggling that `!=` does
However, a better method is to use the isset() function which checks if a variable or key in an array exists like so:
if (isset($_POST['send']))
If you were to enable full error reporting, you may get some notices that the $_POST['key'] and $_POST['send'] variables don't exist. With my recommendation that uses isset(), you won't need the $send variable anymore, and the other notice will go away if assign the value to the $key variable after you check that the $_POST['send'] variable is set.

Keep Request when requesting same route with POST and GET?

I'm trying to make a simple form that is validated and errors should be shown. Also, the values of the fields should stay.
I'm using simple routing code to determine which page to show.
My problem is that the values of the form always reset when I submit it.
I googled a bit and found that when the Request changes, the form values get lost.
That's a small example that shows what I want to achieve:
$route = $_SERVER['REQUEST_URI'];
switch ($route) {
case '/kontakt':
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test">
<input type="submit">
</form><?php
break;
}
After submitting the entered value should stay in the field.
So how can I keep the Request when routing to the same route but one time with POST and one time with GET without changing the form value to use the _POST array?
Lets first grab which request we need to use to get the request arguments.
$request =& $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
It would probably be a good idea here to check it is set, if it isn't - just leave it blank.
$name = $request['name'] ?? ''; # PHP 7+
$name = isset($request['name']) ? $request['name'] : ''; # PHP 5.6 >
You can then do your routing
# switch: endswitch; for readability
switch(($route = $_SERVER['REQUEST_URI'])):
case '/kontack': ?>
<form method="POST" action="/kontakt">
<input type='text' value='<?= $name; ?>' name='name' />
....
<?php break;
endswitch;
This will then continuously insert the name back in to the value field. However, if you visit a new page and then come back - it will be gone. If you want it to stay at all times, through-out any route, you can use sessions.
session_start();
# We want to use the request name before we use the session in-case the user
# Used a different name to what we previously knew
$name = $request['name'] ?? $_SESSION['name'] ?? ''; # PHP 7
$name = isset($request['name']) ? $request['name'] : isset($_SESSION['name']) ? $_SESSION['name'] : ''; # PHP 5.6 >
# Update what we know
$_SESSION['name'] = $name;
Note: I showed both PHP 5.6> and PHP 7 examples. You only need to use one based on which PHP version you're using.
When you are getting to the route in the first time, then send a HTML-valueAttribute-variable as null. When you go back to the route after posting send the post value to the HTML-valueAttribute-variable:
When you reach the route the first time:
<?php
//Value that is sent to the view/page when accessing route without having posted a value
$testValue=null
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>
When you use the route after have posted:
<?php
//Value that was posted is sent to view/page
$testValue=$POST['test']
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>

isset function doesn't work on my form and form is nod getting submitted

I am submitting form to page and checking if submit button value InsertMe isset but non of the code inside is executed
<?php
if (isset($_POST['InsertMe'])){
//code to execute
echo "Test";
}
?>
and insert buttons looks like that
<input style="float:right;" name="InsertMe" id="InsertMe" type="submit" class="rectangular-button" value="Add User" />
if (!isset($_POST['InsertMe']) || empty($_POST['InsertMe'])) {
// error message here
} else {
// What you want to do if not empty and is set.
}
This code will check if the variables is set and if if it's empty.
"||" is the PHP operator to check or. So in this case it's checking if it's set OR empty.
Make sure you have the form tag set to post.
<form method="post">
you are selecting Id I think we should be use name tag parameters in isset()

Need type="text" input fields to display previously-POST'd entries if errors occur

I've probably not explained what I"m trying to do in the title very well, so here goes:
I've got a HTML entry form, in a .php file. That entry form when submitted files a POST operation. That POST operation has code to check field input, similar to this:
<?php
...
if ($_POST["submitted"] == 1) {
//"submitted" is a hidden field with value '1' in the form
$isvalid = 1; // Inits to 1, changes to 0 if something fails checks.
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
...
/*
Checks for validation on each field go here,
but are not relevant to this question here.
*/
}
if ($isvalid == 1) {
// Send email
} else { ?>
<!-- Print form, and error msg. -->
...
<input name="field1" type="text" id="field1" size="32" class="stylingclass">
...
So the above is example code, but here's the real question: How can I get any of the text input fields in my form, when submitted and an error occurred, to automatically contain the previous values that were entered, so that the user can correct the entries accordingly, based on whatever constraints I've set?
You can set the value parameter using a basic ternary operator:
<input name="field1" type="text" id="field1" value="<?php echo isset($_POST["field1"]) ? $_POST["field1"] : ''; ?>" size="32" class="stylingclass">
Note that the ternary operator is used here to prevent an error if there is no index of the specified field in the $_POST array
Just add value="<?=$_POST['field1']?>" (assuming PHP 5.4, use <?php echo $_POST['field1'] ?> otherwise)

How to mantain values if submit fails PHP

I have a form that is being validated using PHP server side scripting. The form's action is also to itself. To show multiple errors, I store it in an array and used foreach to loop through the values and echo it for dislay. I thought i'm finished using PHP validation but I noticed that everytime I submit the form, even though it still contains some errors, all of the values that were inputted resets. Why? When I used javascript, the values remains so whats with PHP?
This is how I set my errors and insert data to db.
if(isset($_POST["submit"]))
{
$lname = $_POST["lname"];
$errors = array();
if(strlen($lname) == 0)
{
$errors[] = "Last name is required";
}
if (!empty(errors))
{
//display errors using foreach loop
}
else
{
//connect and insert data to mysql db
}
}
?>
You perhaps write your HTML form without setting up default values.
<input type="text" name="firstname" />
In the case of an error you should set up a default value. Here an example. Do not forget to sanitize your POST vars before outputting.
<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" />
in your form's input element code use it like this
<input type="text" name="username" value="<?php if(isset($_POST['username']) echo $_POST['username'];?>">
using isset to check if value exist or not and than echoing it

Categories