JAVA SCRIPT - Populating a Selection List from the Server - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Populating a Selection List from the Server - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, January 3, 2019

JAVA SCRIPT - Populating a Selection List from the Server

Populating a Selection List from the Server


Problem

Based on a user’s actions with another form element, you want to populate a selection list with values.

Solution

Capture the change event for the form element: 

document.getElementById("nicething").onchange=populateSelect;
In the event handler function, make an Ajax call with the form data:
var url = "nicething.php?nicething=" + value;
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = getThings;
xmlhttp.send(null);
In the Ajax result function, populate the selection list:
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var select = document.getElementById("nicestuff");
 select.length=0;
 var nicethings = xmlhttp.responseText.split(",");
 for (var i = 0; i < nicethings.length; i++) {
 select.options[select.length] =
 new Option(nicethings[i],nicethings[i]);
 }
select.style.display="block";
} else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
 document.getElementById('nicestuff').innerHTML =
 'Error: Search Failed!';
}

EXPLAIN

One of the more common forms of Ajax is to populate a select or other form element based on a choice made by the user. Instead of populating a select element with many options, or building a set of 10 or 20 radio buttons, you can capture the user’s choice in another form element, query a server application based on the value, and build the other form elements based on the value—all without leaving the page. 


demonstrates a simple page that captures the change event for radio but‐ tons within a fieldset element, makes an Ajax query with the value of the selected radio button, and populates a selection list by parsing the returned option list.

A comma separates each of the option items, and new options are created with the returned text having both an option label and option value. Before populating the select element, its length is set to 0. This is a quick and easy way to truncate the select element— removing all existing options, and starting fresh. 

 Creating an on-demand select Ajax application


<!DOCTYPE html>
<head>
<title>On Demand Select</title>
<style>
#nicestuff
{
 display: none;
 margin: 10px 0;
}
#nicething
{
 width: 400px;
}
</style>
</head>
<body>
<form action="backuppage.php" method="get">
 <p>Select one:</p>
 <fieldset id="nicething">
 <input type="radio" name="nicethings" value="bird" />
 <label for="bird">Birds</label><br />
 <input type="radio" name="nicethings" value="flower" />
 <label for="flower">Flowers</label><br />
 <input type="radio" name="nicethings" value="sweets" />
<label for="sweets">Sweets</label><br />
 <input type="radio" name="nicethings" value="cuddles" />
 <label for="cuddles">Cute Critters</label>
 </fieldset>
 <input type="submit" id="submitbutton" value="get nice things" />
 <select id="nicestuff"></select>
</form>
<script>
var xmlhttp;
function populateSelect() {
 var value;
 var inputs = this.getElementsByTagName('input');
 for (var i = 0; i < inputs.length; i++) {
 if (inputs[i].checked) {
 value = inputs[i].value;
 break;
 }
 }
 // prepare request
 if (!xmlhttp) {
 xmlhttp = new XMLHttpRequest();
 }
 var url = "nicething.php?nicething=" + value;
 xmlhttp.open('GET', url, true);
 xmlhttp.onreadystatechange = getThings;
 xmlhttp.send(null);
}
// process return
function getThings() {
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var select = document.getElementById("nicestuff");
 select.length=0;
 var nicethings = xmlhttp.responseText.split(",");
 for (var i = 0; i < nicethings.length; i++) {
 select.options[select.length] =
 new Option(nicethings[i], nicethings[i]);
 }
 select.style.display="block";
 } else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
 alert("No items returned for request");
 }
}
document.getElementById("submitbutton").style.display="none";
document.getElementById("nicething").onclick=populateSelect;
</script>
</body>

The form does have an assigned action page, and a submit button that’s hidden when the script is first run. These are the backup if scripting is turned off. The application is also old school—text-based data that you can either append directly to the page (if for‐ matted as HTML), or parse using the String functions.

JSON is nice, but there’s always room for just plain text. The example uses a PHP application to populate the selection list. It could also be a Node application if you want to use JavaScript in both the client and server:

<?php
//If no search string is passed, then we can't search
if(empty($_REQUEST['nicething'])) {
 echo "No State Sent";
} else {
 //Remove whitespace from beginning & end of passed search.
 $search = trim($_REQUEST['nicething']);
 switch($search) {
 case "cuddles" :
 $result = "puppies,kittens,gerbils";
 break;
 case "sweets" :
 $result = "licorice,cake,cookies,custard";
 break;
 case "bird" :
 $result = "robin,mockingbird,finch,dove";
 break;
 case "flower" :
 $result = "roses,lilys,daffodils,pansies";
 break;
 default :
 $result = "No Nice Things Found";
 break;
 }
 echo $result;
}
?>


Progressively building form elements using Ajax or another communication technique isn’t necessary in all applications, but it is a great way to ensure a more effective form in cases where the data can change, or the form is complex.

No comments:

Post a Comment

Post Top Ad