There was a need recently to develop a small object that generated a Drop-down form based on data from AJAX requests.
This demand often arises, such as the choice of addresses around the world, the provinces and cities of all the countries in the world are a lot of data, and the form is not necessarily used. Consider loading an empty form first, loading the data with AJAX when the user clicks, or loading the list of all countries and then loading the corresponding provinces and cities according to the user's chosen country.
For example, some of the places where you must use AJAX to load a drop-down form. Like CDK Redemption, users are required to fill out the CDK and then generate a drop-down form according to the range of CDK applicable.
Implementing this functionality is simpler, but we're talking about how to implement this function more efficiently.
HTML form
Before AJAX gets and generates data, you first need an empty or existing HTML drop-down form to populate the data:
<select id= "Dropdown" >
<option value= "" > Please select ...</option>
</select>
AJAX Fetch Data
Next we can start using AJAX to get the data, and in the case of JQuery, Ajax gets the data very easy.
The time to get the data is when the user clicks on the form, the user sets the contents of the other forms, or other times.
$.ajax ({
Type: ' Get ',
Url:ajaxurl,
DataType: ' JSON ',
Success:function (data) {
Build_dropdown (data, $ (' #dropdown '), ' Please select ... '); /Fill out the form
}
} );
Using AJAX to request Ajaxurl's address will return a JSON object, and then we need to parse the data and populate it with the dropdown form, which uses the custom method Build_dropdown ().
Filling out forms
After retrieving the data using the Ajax () method on the top, populating the form data with the Build_dropdown () method, here we create this method:
Filling out forms
var build_dropdown = function (data, element, DefaultText) {
Element.empty (). Append (' <option value= ' "> ' + defaulttext + ' </option> ');
if (data) {
$.each (data, function (key, value) {
Element.append (' <option value= ' + key + ' "> ' + value + ' </option> ');
} );
}
}
This method uses three parameters, namely, the form data (JSON object), the form that needs to be populated, and the text of the default empty option.
Here you can complete a process of AJAX fetching data and generating a drop-down form.
Data format
AJAX gets the form data as a JSON object, in a format similar to the following:
{
' USA ': ' America ',
' Chinese ': ' China ',
' Japan ': ' Japanese ',
' Germany ': ' Germany ',
' Britain ': ' England ',
' France ': ' France ',
' Korea ': ' Korea '
}
You can use PHP's Json_encode () function to turn PHP data into the JSON object data we need:
Echo Json_encode Array (
' USA ' => ' America ',
' China ' => ' Chinese ',
' Japanese ' => ' Japan ',
' Germany ' => ' Germany ',
' Britain ' => ' England ',
' France ' => ' France ',
' Korea ' => ' Korea '
) );