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.