sodaddict
sodaddict

Reputation: 37

(PHP) I can't get a form action PHP code to work

I am not sure what i am doing wrong, but i cannot get a PHP form action page to work, when i attempt to run it, it takes me to a blank page that does nothing. I am trying to create a simple code that redirects the user to a page depending on the input on the form. Here is what my form code looks like:

<form action="index.php" method="post">
<font face="Stymie">ENTER SECRET CODE: <input type="text" name="secretcode"></font>
</form>

and here is what the index.php currently looks like:

<html>
<body>
<?php
    if ($_POST['secretcode'] === "banana") {
        header("Location: banana.php");
    }
?>
</body>
</html> 

This is one out of many codes i attempted to use, yet no matter what i put, it always takes me to a blank page. I also tried using GET instead of POST, but that just leaves me on the page without the code running. Can someone tell me what i am suppose to do to get the code working? Help would be much appreciated.

UPDATE: I found a Javascript equivalent to this script which is a lot more efficient and simpler, thus i no longer need an answer.

<form onSubmit="return checkAnswer();">

<script>
function checkAnswer(){
var response = document.getElementById('secretcode').value;
if (response == "banana")
location = 'banana.html';
else
location = 'wrong.html';
return false;
}
</script>

Upvotes: 0

Views: 1929

Answers (1)

Carl Binalla
Carl Binalla

Reputation: 5401

Add a submit button:

<form action="index.php" method="post">
    <font face="Stymie">ENTER SECRET CODE: <input type="text" name="secretcode"></font>
    <button type="submit" name="submit" value="Enter"/>
</form>

And for the php code:

<?php
    if (isset($_POST['submit'])) {
       if($_POST['secretcode'] === "banana"){
          header("Location: banana.php");
       }
    }
?>

I added the isset() to prevent possible Undefined index: errors when you expand the php codes

UPDATE

I just tried OP's codes, it is submitting even without a submit button (didn't know that, or maybe I just forgot).

It seems working for me, I am being redirected to banana.php when I typed banana in the input, the only problem I saw is the Undefined index error (which the isset() will solve it)

Upvotes: 3

Related Questions