0

Can this be done?

I created a form which performs the function giveReaction. Can anybody tell me what I'm doing wrong?

This is my code so far:

function giveReaction (){
    global $firstname;
    if ( empty($firstname) ) {
        $firstname = 'fill in your name, and get a response.';
        echo "$firstname";
    }
    else {
        $firstname = $_GET['firstname'];
        echo "hello, $firstname";
    }
}

echo "<form action=\"index.php?func_name=giveReaction()\" method=\"GET\">
        <input type=\"text\" name=\"firstname\">
        <input type=\"submit\" value=\"send\">
      </form>";

giveReaction();
2
  • I bet you're falling in the else all the time, right? Say what's the problem if not. Commented Apr 1, 2016 at 0:47
  • 1
    You never set $firstname. Take a look at some php forms tutorial Commented Apr 1, 2016 at 0:49

2 Answers 2

1

There are a two immediate problems with your code:

  1. You never define $firstname prior to checking it's empty
  2. The action in your form does nothing, as you never handle func_name - this is not a built in feature of the language

To start fixing your code, you need to correctly handle the firstname input when the form has been submitted, for example:

$firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';

This ensures that $firstname will be the submitted value, or an empty string if it hasn't been provided yet.

So then you can define your function as follows:

function giveReaction (){
    $firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';
    if ( empty($firstname) ) {
        echo 'fill in your name, and get a response.';
    } else {
        echo "hello, $firstname";
    }
}

Secondly adjust your form to remove the unnecessary action, as by default forms will submit to the current page, and the func_name parameter isn't used.

echo "<form method=\"GET\">
    <input type=\"text\" name=\"firstname\">
    <input type=\"submit\" value=\"send\">
  </form>";

Then you can finish as you have, by calling your function.

giveReaction();
Sign up to request clarification or add additional context in comments.

Comments

0

Your function can simply be:

function giveReaction() {
  $firstname = $_GET['firstname'];
  echo $firstname ? "hello, $firstname" : 'fill in your name, and get a response.';
}

There's no need to add it to the form.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.