PHP form that loads content based on dropdown option

html, php, wordpress

Solution

You can get around this problem in many ways, but in this case I would recommend two ways: PHP or JS.

Solution 1, PHP

You will need

1) A form

<form action="loadPage.php" method="POST" name="theForm" id="theForm">
<select form="theForm" name="selectedPage">
  <option value="page_1">Page 1</option>
  <option value="page_2">Page 2</option>
  ...
</select>
<input type="submit" value="Load page" />
</form>

2) A PHP handler

//loadPage.php
<?php
$requested_page = $_POST['selectedPage'];

switch($requested_page) {
  case "page_1":
    header("Location: page_1.php");
  break;
  case "page_2":
    header("Location: page_2.php");
  break;
  default :
  echo "No page was selected";
  break;
}
?>

Solution 2, Javascript

Let's say that you'd like to display different pages without using PHP, then what to choose? JavaScript. This is, to me, more easy to implement and much more "user-friendly" :

Task: Display different pages from the same form

<!DOCTYPE html>
<html>
<head>
<!-- Amazing stuff goes here :) -->
<script>
function load_page() {
    var selected_page = document.getElementById("selected_page").value;
    if (selected_page != "") {
        window.location.href = selected_page
        //Please note that the value recived,
        //in this case selected_page,
        //should be a valid url!
        //Therefore the value of the
        //<option> tag should be itself 
        //a url !
        //ex.: <option value="page.php"> is valid
        //<option value="page_1"> is not valid
    }
}
</script>
</head>
<body>
<form action="#">
    <select id="selected_page">
        <option value="page_1.php">Page 1</option>
        <option value="page_2.php">Page 2</option>
        ...
    </select>
    <button onclick="load_page()">Load it ! </button>
</form>
</body>
</html>

Problem

I have already asked a question regarding this issue here, for a client project. Those answers may not be what I am looking for, so I will try to make this question as detailed as possible. I have a form which has 4 main pages. The first page asks for personal information. Clicking on Submit takes you to a second page. Second page has a dropdown list containing item numbers. Let's say they are A, B, C, D, E. When a visitor chooses an item and clicks submit, I want the next page to show content based on the item chosen above: - If visitor chooses option A, the page should load the html page a.html or php page a.php. - If he selects option B, the page should load the html page b.html or php page b.php. And so on for other items, each one having a different page. I don't know PHP in detail. I am building this form in a website on WordPress.

Original source