Collecting data from an HTML form filled out by users

I need a way to capture user input from an HTML form and display it later on my website. I want to show all the information users provide along with their pizza selections. I've been struggling for hours trying to make this work without success :( Specifically, I am looking to collect the date, first name, last name, address, and phone number.

<!DOCTYPE html>
<html>
<head>
    <meta  charset="utf-8" />
    <title>Daves Pizza</title>    
    <link href="new.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="pizza.js"></script>
</head>
<body>
    <div align="center">
        <h5>Today is: <span id="dtfield"></span></h5>
    </div>
    <br>
    <div align="center">
        <h1>Dave's Pizza Place</h1>
    </div>
    <div align="center">
        <div class="user">
            <form id="contact_form" action="mailto: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="056164736c612b62606b6260456061702b76646c712b6664">[email protected]</a>" name="userInfo" method="POST" enctype="text">
            <br>
                <div>
                    <label for="datetime">Date:</label>
                    <input type="date" name="user_date" />
                </div>
                <div>
                    <label for="firstname">Firstname:</label>
                    <input type="text" pattern="[A-Za-z-']+" name="firstname" value="Firstname" maxlength="20"/>
                </div>
                <div>
                    <label for="lastname">Lastname:</label>
                    <input type="text" pattern="[A-Za-z-']+" name="lastname" placeholder="Lastname" maxlength="20"/>
                </div>
                <div>
                    <label for="mail">Address:</label>
                    <input type="text" name="user_mail" placeholder="Full  Address"/>
                </div>
                <div>
                    <label for="tel">Phone#:</label>
                    <input type="tel" pattern="[0-9]+"" name="user_phone" placeholder="(403)123-1234"/>
             </div>
            </form>
        </div>
    </div>
    <div align="center">
        <div class="pizza">
            <form name="costEstimation">
                <table border="0">
                    <tr valign="middle">
                        <td>
                            <br>
                            <b>Choose Your Pizza Type<b><br>
                                <input type="radio" name="pizzasize" value="8" checked>Small $8<br>
                                <input type="radio" name="pizzasize" value="10">Medium $10<br>
                                <input type="radio" name="pizzasize" value="15">Large $15<br>
                                <input type="radio" name="pizzasize" value="18">Extra Large $18<br></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>
                            <b>Specialities<b><br>
                                <input type="radio" name="special" value="3">Super Cheesy $3<br>
                                <input type="radio" name="special" value="5">Extra Meaty $5<br>
                                <input type="radio" name="special" value="2">Really Veggie $2<br></td>
                        <td>
                            <b>Extra Toppings </b>
                            <br>
                            <input type="checkbox" name="cheese" value="1.5">Extra Cheese $1.50<br>
                            <input type="checkbox" name="pepperoni" value="1.5">Pepperoni $1.50<br>
                            <input type="checkbox" name="mushrooms" value="1.5">Mushrooms $1.50<br>
                            <input type="checkbox" name="bacon" value="1.5">Bacon $1.50<br>
                            <input type="checkbox" name="olives" value="1.5">Olives $1.50<br>
                        </td>
                    </tr>
                </table>
            </form>
            <h2>Pizza Cost: </h2><h2><span id="result"></span></h2>
                <input type=button value="Price Your Pizza" onClick="pizza(); return false;">
                <button type="submit">Send your message</button>
            <br><br><br>
            <table>
                <tr>
                    <td>
                        <figure>
                            <center>
                                <img  src="cheese.jpg"  alt="cheese" height="100" width="100">
                            </center>
                        </figure>
                    </td>

                    <td>
                        <figure>
                            <center>
                                <img src="veg.jpg"  alt="veg" height="100" width="100">
                            </center>
                        </figure>
                    </td>

                    <td>
                        <figure>
                            <center>
                                <img src="meat.jpg" alt="meat" height="100" width="100">
                            </center>
                        </figure>
                    </td>
                </tr>
            </table>
        </div>
        <br>
        <br>
        <br>
    </div>
</body>
</html>

Answer №1

To save the input values provided by a user, you must utilize the form element. This can be achieved through either the GET or POST method. Below is a demonstration with validation included:

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// declaring variables and initializing them as empty
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // checking if name contains only letters and white spaces
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // ensuring email address format is valid
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }

  // additional code for validating website and comment inputs

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* denotes required fields.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  // form elements for email, website, comments, gender
  
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

Answer №2

When creating interactive web applications, it is essential to utilize a server-side language for receiving input from users.

To accomplish this task, include the following code snippet:

<form method="GET or POST" action="file_location/file_name(where you want to receive input)">

An excellent choice for beginners is PHP due to its simplicity. Here's an example to help you understand:

index.html

<form method="GET" action="localhost://getdata.php"> 
<input type="text" name="UserName" />
<input type="button" value="Submit" />
</form>

Pay attention to the "name" attribute used in the input tag as 'UserName'. This will store user input data, which can be accessed and displayed with PHP as demonstrated below:

getdata.php

<?php
echo "$_GET['UserName']";
?>

Answer №3

if you need to retrieve the information using JavaScript, follow these guidelines:

HTML:

  <input type="text" name="name" id="specificID" value="data" />
  <span id="result"></span>

JS:

var info = document.getElementById("specificID").value;
document.getElementById("output").innerHTML=info;

This approach should be helpful for your situation!

Answer №4

<!DOCTYPE html>
<html>
<head>
    <meta  charset="utf-8" />
    <title>Dave's Pizzeria</title>    
    <link href="menu.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="pizzeria.js"></script>
    </head>
<body>
    <div align="center">
        <h5>Date: <span id="dateField"></span></h5>
    </div>
    <br>
    <div align="center">
        <h1>Dave's Pizza Palace</h1>
    </div>
    <div align="center">
        <div class="customerInfo">
            <form id="contact_form" action="mailto: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6f6a7d626f256c6e656c6e4b6e6f7e25786a627f25686a">[email protected]</a>" name="userInfoForm" method="POST" enctype="text">
            <br>
                <div>
                    <label for="datetime">Date:</label>
                    <input type="date" name="user_date" />
                </div>
                <div>
                    <label for="firstname">First Name:</label>
                    <input type="text" pattern="[A-Za-z-']+" name="firstname" value="First Name" maxlength="20"/>
                </div>
                <div>
                    <label for="lastname">Last Name:</label>
                    <input type="text" pattern="[A-Za-z-']+" name="lastname" placeholder="Last Name" maxlength="20"/>
                </div>
                <div>
                    <label for="mail">Address:</label>
                    <input type="text" name="user_mail" placeholder="Full Address"/>
                </div>
                <div>
                    <label for="tel">Phone Number:</label>
                    <input type="tel" pattern="[0-9]+"" name="user_phone" placeholder="(403)123-1234"/>
                </div>
            </form>
        </div>
    </div>
    <div align="center">
        <div class="pizzaMenu">
            <form name="costEstimation">
                <table border="0">
                    <tr valign="middle">
                        <td>
                            <br>
                            <b>Select Your Pizza Size<b><br>
                                <input type="radio" name="pizzaSize" value="8" checked>Small $8<br>
                                <input type="radio" name="pizzaSize" value="10">Medium $10<br>
                                <input type="radio" name="pizzaSize" value="15">Large $15<br>
                                <input type="radio" name="pizzaSize" value="18">Extra Large $18<br></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td>
                            <b>Specialties:<b><br>
                                <input type="radio" name="special" value="3">Super Cheesy $3<br>
                                <input type="radio" name="special" value="5">Extra Meaty $5<br>
                                <input type="radio" name="special" value="2">Really Veggie $2<br></td>
                        <td>
                            <b>Add Extra Toppings </b>
                            <br>
                            <!-- Add checkbox options here -->
                        </td>
                    </tr>
                </table>
            </form>
            <h2>Pizza Total Cost: </h2><h2><span id="totalCost"></span></h2>
                <input type=button value="Calculate Price" onClick="calculateTotal(); return false;">
                <button type="submit">Submit Order</button>
            <br><br><br>
            <table>
                <tr>
                    <td>
                        <figure>
                            <center>
                                <img  src="cheese.jpg"  alt="cheese" height="100" width="100">
                            </center>
                        </figure>
                    </td>

                    <td>
                        <figure>
                            <center>
                                <img src="veg.jpg"  alt="vegetable pizza" height="100" width="100">
                            </center>
                        </figure>
                    </td>

                    <td>
                        <figure>
                            <center>
                                <img src="meat.jpg" alt="meat pizza" height="100" width="100">
                            </center>
                        </figure>
                    </td>
                </tr>
            </table>
        </div>
        <br>
        <br>
        <br>
    </div>
</body>
</html>

Answer №5

<html lang="en">
<head>
    <title>Dave’s Burger Joint</title>

    <!-- Recommended meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

    <!-- PyScript CSS -->
    <link rel="stylesheet" href="https://pyscript.net/releases/2023.12.1/core.css">

    <!-- This script tag bootstraps PyScript -->
    <script type="module" src="https://pyscript.net/releases/2023.12.1/core.js"></script>

    <link rel="manifest" href="./psadc-manifest.json">
</head>
<body>
<div align="center">
        <h1>Dave's Pizza Place</h1>
</div>
<div>
    <label for="datetime">Date:</label>
     &ensp; &ensp; &ensp; &ensp;<input type="date" id="input1" name="user_date" />
</div>
<div>
    <label for="firstname">Firstname:</label>
     &ensp;<input type="text" pattern="[A-Za-z-']+" id="input2" name="firstname" placeholder="firstname" maxlength="20"/>
</div>
<div>
    <label for="lastname">Lastname:</label>
     &ensp;<input type="text" pattern="[A-Za-z-']+" id="input3" name="lastname" placeholder="Lastname" maxlength="20"/>
</div> 
<div>
    <label for="mail">Address:</label>
     &ensp; &ensp;<input type="text" name="user_mail" id="input4" placeholder="Full  Address"/>
</div>
<div>
    <label for="tel">Phone#:</label>
     &ensp; &ensp;<input type="tel" id="input5" pattern="[0-9]+"" name="user_phone" placeholder="(403)123-1234"/>
</div>
<p></p>    
<form>
  <fieldset>
    <legend>Choose Your Burger Type:</legend>
    <div>
      <input type="radio" id="8" name="contact" value="8"  checked/>
      <label for="contactChoice1">Classic Beef ($8)</label>

      <input type="radio" id="contactChoice2" name="contact" value="10" />
      <label for="contactChoice2">Chicken Mushroom ($10)</label>

      <input type="radio" id="contactChoice3" name="contact" value="15" />
      <label for="contactChoice3">Vegan Quinoa ($15)</label>

      <input type="radio" id="contactChoice4" name="contact" value="18" />
      <label for="contactChoice3">BBQ Turkey ($18)</label>  
    </div>
  </fieldset>
</form>
<p></p>    
<form>
  <fieldset>
    <legend>Add-ons:</legend>
    <div>
      <input type="checkbox" id="contactChoice1" name="contact1" value="2.50"  checked/>
      <label for="contactChoice1">Bacon (+$2.50)</label>

      <input type="checkbox" id="contactChoice2" name="contact1" value="1" />
      <label for="contactChoice2">Avocado (+$1)</label>

      <input type="checkbox" id="contactChoice3" name="contact1" value="1.50" />
      <label for="contactChoice3">Fried Egg (+$1.50)</label>
    </div>
  </fieldset>
</form> 
<p></p>    
<button py-click="myFunction" id="add">Build Your Burger</button>
<p></p>
<script type="py">
from pyscript import display
from datetime import datetime
now = datetime.now()    
def myFunction(event): 
       from pyscript import document
       Date = document.getElementById("input1").value
       Firstname = document.getElementById("input2").value
       Lastname = document.getElementById("input3").value
       Address = document.getElementById("input4").value
       Phone = document.getElementById("input5").value
       t = now.strftime("%m/%d/%Y, %H:%M:%S")
       rate2=[]
       rate = document.querySelector('input[name="contact"]:checked').value
       rate1 = document.querySelector('input[name="contact1"]:checked').value
       checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
       for i in range(checkboxes.length):
           rate2.append(checkboxes[i].value)
       display(f"Today is: {t}")
       display(f"Date: {Date}")
       display(f"Firstname: {Firstname}")
       display(f"Lastname: {Lastname}")
       display(f"Address: {Address}")
       display(f"Phone: {Phone}")
       s1 = list(map(float, rate2))
       s1 = (sum(s1))
       display(f"Total cost: ${int(rate)+int(rate1)+int(s1)}")
</script>
</html>   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to manage the back button functionality on pages that use templates?

I am currently developing a website using angularjs. The layout consists of two main sections: the menu and the content area. For instance This is an example page: /mainpage <div> <div id="menu"> <div ng-click="setTemplate('fi ...

Container beyond div

Having an issue with the div extending beyond the container in Bootstrap 4. When a green div reaches the edge of the page, instead of being cut off it causes a horizontal shift in the page layout. How can this be avoided? Appreciate any assistance. Live ...

Passing an array from the PHP View to a JavaScript function and plotting it

Greetings, I am currently facing the following tasks: Retrieving data from a database and saving it to an array (CHECK) Sending the array from Controller to View (CHECK) Passing that array to a JavaScript function using json_encode (CHECK) Plotting the ...

Replica of Spotify - Bottom Section - HTML and CSS Styling

I have been attempting to replicate the Spotify interface using only HTML and CSS. While I have successfully created the player section, I am struggling to center the player and incorporate the other two details as shown in the attached images. The 'G ...

AngularJS Vimeo API Request Error: "401 Authorization Required"

I've been experimenting with making external API calls to Vimeo from my AngularJS code using $http.jsonp. However, I keep receiving a 401 Authorization required error even though I have included my authorization key in the header. I encountered a simi ...

Incorporating a scrollbar when a div exceeds the bottom of the viewport

I am encountering an issue on my webpage with a <div> that contains a <table> with rows of varying heights: <html> <head></head> <body> <div> <table> <tr>... <tr>... ... </ ...

Transmit an array in a post request with Node.js using the application/x-www-form-urlencoded content type

After attempting to send a post request to an API with post parameters as an array, I encountered difficulties. Here is how it can be done using cURL: curl http://localhost:3000/check_amounts -d amounts[]=15 \ -d amounts[]=30 I then tried to ach ...

Store the checkbox's data in the database for safekeeping

Hey there, I'm working on saving the value of a checkbox using PHP. The twist is that the value is generated through JavaScript. How can I handle this scenario and save the value using PHP? Checkbox: <input type='checkbox' name='ca ...

Modify the hover color of <TextField /> within the createMuiTheme() function

Is there a way to change the borderColor on hover for the outlined <TextField /> Component within the createMuiTheme()? I have managed to do it easily for the underlined <Input /> export default createMuiTheme({ MuiInput: { &apo ...

What is the best way to include a parameter in the current URL in Django using Paginator?

After setting up a page to display database data, I added a paginator and a search bar to my website. When a user searches for something, the URL changes to include the search query like this: .../search/?q=xyz However, when paginating the search results ...

Incorporating pre-designed elements into the bottom section of my

I'm currently facing an issue while trying to integrate a footer content from a template into my slideout footer. The problem is that the template footer is currently spanning across the entire width of the page, and I am struggling to contain it with ...

What is the process for refreshing a user's session from the backend following updates to their metadata?

Currently, I am utilizing Next.js on the client side, auth0 for authentication, and Django Rest Framework for the backend. By following Auth0's Manage Metadata Using the Management API guide, I successfully managed to set new metadata values (verified ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

Does using breakpoints in strict mode affect the outcome?

Here is the code snippet: 'use strict'; var foo=function(){ alert(this); } var bar = { baz:foo, }; var x = bar.baz; x();//1 After executing the code directly, everything works fine and it alerts undefined. However, when I insert a break ...

My DIV elements are not responding to the widths I set for them. What could be the issue?

Recently, I've been delving into the world of Flex to experiment with some unique layouts. However, I encountered an issue where my divs were not recognizing widths as expected. I attempted to set the first div of each row to 5% width so they would ...

How can you adjust the div orientation for small screens using Bootstrap?

I've been working with Bootstrap and I'm facing an issue with the orientation of a div on small screens. On medium screens, I have two columns set to 6, 6 which should stack on top of each other on smaller screens. Here's how I want it to lo ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

Having trouble getting a form to submit to a Rails server using AJAX in IE11 with jQuery

Currently, I'm attempting to transfer data from a form to a Rails server using AJAX. The form consists of two text inputs and one file input. Below is the code for my submit event handler: $("form").on("submit", function(event) { event.preventDefa ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...