Web Programming Header

CODE PAGE

CGI Format - Collecting Data

Forms pass CGI (Common Gateway Interface) format data when they are submitted. This can be seen on the browser bar if the form method is GET. It is hidden if the form method is POST but the data is still sent. Below we provide sample code of collecting this data in JavaScript. We will also see how to collect it with a server script in the next module.

// CGI format - the part after the filename and extension
// the special value is the encoded value for "you got 50% & pass!"
somepage.html?var1=val1&var2=val2&special=you+got+50%25+%26+pass%21

Forms will automatically encode and server scripts will automatically decode. But you can use encodeURIComponent() and decodeURIComponent() to manually encode and decode - but be careful you do not double encode or decode.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Gifts</title>
    </head>
    <body>
        <p>This form will figure your ideal gift:</p>
        <form action="result.html" method="get">
<table>
    <tr>
        <td><label for="name">Enter Name:</label></td>
        <td><input type="text" id="name" name="name"></td>
    </tr>
    <tr>
        <td><label for="personality">Personality?</label></td>
        <td>
            <input type="radio" value="grouchy" name="personality"> Grouchy
            <input type="radio" value="emo" name="personality"> Emo
            <input type="radio" value="happy" name="personality"> Happy
        </td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" name="submit" value="Predict!"></td>
    </tr>
</table>
        </form>
    </body>
</html>   

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Present Results</title>
        <script>
            window.addEventListener("DOMContentLoaded", init);
            function init() {
                console.log(location.search);                
                const searchParams = new URLSearchParams(location.search);

                const results = searchParams.get("personality");
                console.log(results);

                const answer = document.getElementById("answer");
                const message = "You get a ";
                if (results == "happy") {
                    answer.innerText = message + "TURTLE";
                } else if (results == "grouchy") {
                    answer.innerText = message + "COLD";
                } else {
                    answer.innerText = message + "STRAW";
                }
            }
        </script>
    </head>
    <body>
        <h1 id=answer>Your Gift is a Watermellon Launcher!</h1>
    </body>
</html>