Link to home
Create AccountLog in
Avatar of Joseph Longo
Joseph LongoFlag for United States of America

asked on

Dynamically Load Different HTML Web Forms

Hello Experts,

I am not sure what would be considered best practice, and what is recommended. I am new to programming and new to PHP in general. I am self-taught, so I am sure my code is vulnerable in areas, etc., and I am sure I am not doing things correctly, per industry-standard. But, I enjoy being creative.

I am working on a website at the moment. The website is designed to create 1 of 4 arrest PDFs, based off the user's input, when asked "What type of arrest would you like to generate?" Each arrest varies in size and each arrest differs from the data collected in order to create it. For instance, the arrest type of "Juvenile Civil Citation" does not collect the person's social security number, eye color, hair color, scars, marks, or tattoos, whereas the arrest type of "NTA" does collect all of that information. Rather than have one massive HTML form which contains unnecessary fields (based off my previous explanation), I would like to have a specific form for each arrest type which only contains the input fields necessary for that type of arrest. Upon submitting the form, the form is processed by PHP and creates the corresponding PDF via FPDF.

Ultimately, I would like to dynamically load each form into the web browser after the end user selects the corresponding arrest from an HTML select element. However, it might be easier to just create four separate HTML pages which have customized forms and then link to each page...

I believe Javascript or JScript is able to accomplish my goal. However, I am reluctant to learn a new programming language when I am just in my infancy stages of learning php...

Any ideas/suggestions?
Avatar of Jonathan D.
Jonathan D.
Flag of Israel image

it might be easier to just create four separate HTML pages which have customized forms and then link to each page...

Exactly, I once had a project to create my own personal blog which had four partial views with the same structure and hardcoded links, etc. So I dynamically loaded each of them (instead of hardcoding them to the main view, which I can change what's needed at a different portion. this is some sort of separation of concerns) with jQuery's html() method attached to the element.

This strategy is like programming, each big repetitive chunk is being chopped down to a recallable function. Same concept goes to html, when you have a big chunk of markup, consider splitting it into smaller partial views (it doesn't have to be strictly asp.net, it could be just plain html markup files) and load them with the method I previously mentioned.

I believe Javascript or JScript is able to accomplish my goal.

jQuery html() method, it injects partial views into the content markup by a tag.
Take a look : https://developer.mozilla.org/fr/docs/Web/CSS/display#display_none
<head>
<style>
   .hide {
       display:none;
   }
</style>
</head>
<body>
<form>
<span>What type of arrest would you like to generate?</span>
<select id="TOA" name="TOA">
  <option>Choose a type of arrest</option>
  <option value="JCT">Juvenile Civil Citation</option>
  <option value="JFF">Just For Fun</option>
</select>
<div id="abcd" class="hide">
   <div><span>SSN :</span><input name="ssn" type="text"></div>
   <div><span>Eye color :</span><input name="ssn" type="text"></div>
</div>
<script>
document.querySelector("TOA").addEventListener("change", function() {    
    if(this.value == "JCT") {
         document.querySelector("abcd").classList.remove("hide");
    } else {
         document.querySelector("abcd").classList.add("hide");
    }
});
</script>

Open in new window

For a starter, who wants to learn: Just do it.

Thus implement it the way you think it is okay. Then we can discuss certain points of it. Cause doing is learning.


The only question is see here is: What kind of system should it gonna be?  

E.g. a "classic" web site or a modern web application or something in between?
Taking the both extremes, mean that you may don't need any JavaScript at all or you application runs completely in JS without any PHP in the backend.
+1 for @ste5an's comment, "For a starter, who wants to learn: Just do it."
How I approach this type of project, which has many moving parts.

1) If you have unlimited time/budget/will/expertise... so no timeline... this is just a lark... not timeline... no requirement for any income to flow in a timely manner... write all your own code...

You'll learn a lot.

If you have any constraints, you'll leverage other code... like...

2) For session/user/role management, use WordPress.

3) You might use some sort of WordPress plugin like Content Restrict Pro (just an example of many), if you provided different membership levels (price points) to access your data.

4) For output file generation, I always use asciidoctor.

So the initial data is generated as a Markdown syntax file (dirt simple), which can then be processed into various output formats - HTML or PDF or Latex or any other format you can conceive.

If no output processor exists, you'll write one or hire someone to write one.
Hey Joseph,

There are a few different ways to approach this. Based on your question, the way I would approach it this. I would use Javascript to bind a 'change' event to your <select> input. The event handler for that would then send a selected value back to your server (a php script), and that script would then load the relevant form and send it back to your page. This would mean a simple JS handler in your HTML page, a separate file for each of your forms, and a simple PHP script to handle the loading of the selected form.

Your HTML could be something along these lines:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>EE // 29214911</title>

        <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.getElementById("getForm").addEventListener("change", function() {
                fetch('get-form.php', {
                    method : 'post',
                    body: JSON.stringify({ form : this.value }),
                }).then(function(response) {
                    return response.text();
                }).then(function(html) {
                    document.getElementById("formWrapper").innerHTML = html
                })
            })
        });
        </script>    
    </head>
    <body>
        <select id="getForm">
            <option value="">Please select your form</option>
            <option value="form1">Form 1</option>
            <option value="form2">Form 2</option>
        </select>

        <div id="formWrapper"></div>       
    </body>
</html>

Open in new window

All we're really doing here is making a POST request to your server (get-form.php) and sending along the value of the selected option. Once we get a response, we're pushing that response (the form) into an element on your page (the formWrapper div).

Your PHP script (get-form.php) could look something like this:

<?php
$input = json_decode(file_get_contents('php://input'));

switch ($input->form) {
    case 'form1':
        include 'form1.partial.php';
        break;

    case 'form2':
        include 'form2.partial.php';
        break;

    default:
        echo 'No valid form selected';
}

Open in new window

And then all that's left to do is to create each form (form1.partial.php, form2.partial.php etc). They would just be standard HTML including all your <form> and <input> tags etc.
I totally agree with David Favor. A lot of the legwork is already done for you using WordPress and a premium form plugin or members plugin. You can still get a chance to code, especially if you're doing a custom job,  just what the client wants!
Avatar of Joseph Longo

ASKER

As some suggested, I hard coded each form, instead. I have a link to each form. Although this was more tedious, it appears to be working nicely 
ASKER CERTIFIED SOLUTION
Avatar of Joseph Longo
Joseph Longo
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account