Filipe Aleixo
Filipe Aleixo

Reputation: 4242

Inserting variable from input in form action

I have a form which queries the user about which type of list he wants to see. As the submit button is pressed, I want to be able to have the value listtype displayed in the address so I can access it by using GET methods, for instance to change the page of the list that is being shown. In this form, I tried the following code:

<?php
    echo '<form method=post action="index.php?operacao=checkList&number=1&pagesize=10&listtype=', $_GET['listtype'] ,'" name="listForm">
    <ol>

        <li><label for="listtype">Type:</label>
        <select name="listtype">
        <option value="default">Select</option>
        <option value="doctor">Doctor</option>
        <option value="nurse">Nurse</option>
        <option value="patient">Patient</option>
        </select></li>

        <div id="form-button">
            <li><input type="submit" value="Submit" onclick="javapopup();"></li>
        </div>

    </ol>
    </form>';
?>

Although, as I open the form, I get an error that says the variable listtype is not defined. How can I solve this problem?

Upvotes: 0

Views: 45

Answers (1)

John Conde
John Conde

Reputation: 219924

$_GET['listtype'] is not going to be set the first time you load this page which is why you are getting this error. You need to check to see if it is set before you use it and, if it is not, not use it in that situation. In your case because your form is set to POST it will never populate the $_GET superglobal which will cause this error to never go away.

echo '<form method=post action="index.php?operacao=checkList&number=1&pagesize=10&listtype=', $_GET['listtype'] ,'" name="listForm">

probably should resemble something like this:

$listype = (isset($_POST['listtype'])) ? $_POST['listtype'] : '';
echo '<form method=post action="index.php?operacao=checkList&number=1&pagesize=10&listtype=', $listype ,'" name="listForm">

FYI, using a raw $_GET or $_POST variable in your code the way you are using it leaves you wide open to Cross Site Scripting attacks. So you should be sanitizing this variable anyway.

$listype = (isset($_POST['listtype'])) ? htmlspecialchars($_POST['listtype']) : '';
echo '<form method=post action="index.php?operacao=checkList&number=1&pagesize=10&listtype=', $listype ,'" name="listForm">

Upvotes: 2

Related Questions