Buy Now
Sign in

How to: Select Country: Get Ajax State/Region/Province field

billthecat , September 15 2010
b
billthecat

The form shows a list of countries, and then receives a list of the State/Region/Province for which ever country is chosen.
Here's the table layout for the select options:

				
<!-- Basic Table Here.... -->
   <tr>
   <td class="style3" style="width: 138px">Country</td>
   <td class="required" style="width: 6px">*</td><td class="sectiontableentry2"><select name="country" onchange="showState(this.value)">
<option value="" selected>Please select a county</option>
<option value="AD">Andorra</option>
<option value="AE">United Arab Emirates</option>
<option value="AF">Afghanistan</option>
<option value="AG">Antigua and Barbuda</option>

<option value="AI">Anguilla</option>
<option value="AL">Albania</option>
<option value="AM">Armenia</option>
<option value="AN">Netherlands Antilles</option>
<option value="AO">Angola</option>
<option value="AQ">Antarctica</option>
<option value="AR">Argentina</option>
<option value="AS">American Samoa</option>
<option value="AT">Austria</option>

<option value="AU">Australia</option>
<option value="AW">Aruba</option>
<option value="AX">Aland Islands</option>
<option value="AZ">Azerbaijan</option>
<option value="BA">Bosnia and Herzegovina</option>
<option value="BB">Barbados</option>
<option value="BD">Bangladesh</option>
<option value="BE">Belgium</option>
<option value="BF">Burkina Faso</option>

<option value="BG">Bulgaria</option>
<option value="BH">Bahrain</option>
<option value="BI">Burundi</option>
<option value="BJ">Benin</option>
<option value="BL">Saint Barthélemy</option>
<option value="BM">Bermuda</option>
<option value="BN">Brunei</option>
<option value="BO">Bolivia</option>
<option value="BR">Brazil</option>

<option value="BS">Bahamas</option>
<option value="BT">Bhutan</option>
<option value="BV">Bouvet Island</option>
<option value="BW">Botswana</option>
<option value="BY">Belarus</option>
<option value="BZ">Belize</option>
<option value="CA">Canada</option>
<option value="CC">Cocos Islands</option>
<option value="CD">Democratic Republic of Congo</option>

<option value="CF">Central African Republic</option>
<option value="CG">Congo</option>
<option value="CH">Switzerland</option>
<option value="CI">Ivory Coast</option>
<option value="CK">Cook Islands</option>
<option value="CL">Chile</option>
<option value="CM">Cameroon</option>
<option value="CN">China</option>
<option value="CO">Colombia</option>

<option value="CR">Costa Rica</option>
<option value="CU">Cuba</option>
<option value="CV">Cape Verde</option>
<option value="CX">Christmas Island</option>
<option value="CY">Cyprus</option>
<option value="CZ">Czech Republic</option>
<option value="DE">Germany</option>
<option value="DJ">Djibouti</option>
<option value="DK">Denmark</option>

<option value="DM">Dominica</option>
<option value="DO">Dominican Republic</option>
<option value="DZ">Algeria</option>
<option value="EC">Ecuador</option>
<option value="EE">Estonia</option>
<option value="EG">Egypt</option>
<option value="EH">Western Sahara</option>
<option value="ER">Eritrea</option>
<option value="ES">Spain</option>

<option value="ET">Ethiopia</option>
<option value="FI">Finland</option>
<option value="FJ">Fiji</option>
<option value="FK">Falkland Islands</option>
<option value="FM">Micronesia</option>
<option value="FO">Faroe Islands</option>
<option value="FR">France</option>
<option value="GA">Gabon</option>
<option value="GB">United Kingdom</option>

<option value="GD">Grenada</option>
<option value="GE">Georgia</option>
<option value="GF">French Guiana</option>
<option value="GG">Guernsey</option>
<option value="GH">Ghana</option>
<option value="GI">Gibraltar</option>
<option value="GL">Greenland</option>
<option value="GM">Gambia</option>
<option value="GN">Guinea</option>

<option value="GP">Guadeloupe</option>
<option value="GQ">Equatorial Guinea</option>
<option value="GR">Greece</option>
<option value="GS">South Georgia and the South Sandwich Islands</option>
<option value="GT">Guatemala</option>
<option value="GU">Guam</option>
<option value="GW">Guinea-Bissau</option>
<option value="GY">Guyana</option>
<option value="HK">Hong Kong</option>

<option value="HM">Heard Island and McDonald Islands</option>
<option value="HN">Honduras</option>
<option value="HR">Croatia</option>
<option value="HT">Haiti</option>
<option value="HU">Hungary</option>
<option value="ID">Indonesia</option>
<option value="IE">Ireland</option>
<option value="IL">Israel</option>
<option value="IM">Isle of Man</option>

<option value="IN">India</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="IQ">Iraq</option>
<option value="IR">Iran</option>
<option value="IS">Iceland</option>
<option value="IT">Italy</option>
<option value="JE">Jersey</option>
<option value="JM">Jamaica</option>
<option value="JO">Jordan</option>

<option value="JP">Japan</option>
<option value="KE">Kenya</option>
<option value="KG">Kyrgyzstan</option>
<option value="KH">Cambodia</option>
<option value="KI">Kiribati</option>
<option value="KM">Comoros</option>
<option value="KN">Saint Kitts and Nevis</option>
<option value="KP">North Korea</option>
<option value="KR">South Korea</option>

<option value="KW">Kuwait</option>
<option value="KY">Cayman Islands</option>
<option value="KZ">Kazakhstan</option>
<option value="LA">Laos</option>
<option value="LB">Lebanon</option>
<option value="LC">Saint Lucia</option>
<option value="LI">Liechtenstein</option>
<option value="LK">Sri Lanka</option>
<option value="LR">Liberia</option>

<option value="LS">Lesotho</option>
<option value="LT">Lithuania</option>
<option value="LU">Luxembourg</option>
<option value="LV">Latvia</option>
<option value="LY">Libya</option>
<option value="MA">Morocco</option>
<option value="MC">Monaco</option>
<option value="MD">Moldova</option>
<option value="ME">Montenegro</option>

<option value="MF">Saint Martin</option>
<option value="MG">Madagascar</option>
<option value="MH">Marshall Islands</option>
<option value="MK">Macedonia</option>
<option value="ML">Mali</option>
<option value="MM">Myanmar</option>
<option value="MN">Mongolia</option>
<option value="MO">Macao</option>
<option value="MP">Northern Mariana Islands</option>

<option value="MQ">Martinique</option>
<option value="MR">Mauritania</option>
<option value="MS">Montserrat</option>
<option value="MT">Malta</option>
<option value="MU">Mauritius</option>
<option value="MV">Maldives</option>
<option value="MW">Malawi</option>
<option value="MX">Mexico</option>
<option value="MY">Malaysia</option>

<option value="MZ">Mozambique</option>
<option value="NA">Namibia</option>
<option value="NC">New Caledonia</option>
<option value="NE">Niger</option>
<option value="NF">Norfolk Island</option>
<option value="NG">Nigeria</option>
<option value="NI">Nicaragua</option>
<option value="NL">Netherlands</option>
<option value="NO">Norway</option>

<option value="NP">Nepal</option>
<option value="NR">Nauru</option>
<option value="NU">Niue</option>
<option value="NZ">New Zealand</option>
<option value="OM">Oman</option>
<option value="PA">Panama</option>
<option value="PE">Peru</option>
<option value="PF">French Polynesia</option>
<option value="PG">Papua New Guinea</option>

<option value="PH">Philippines</option>
<option value="PK">Pakistan</option>
<option value="PL">Poland</option>
<option value="PM">Saint Pierre and Miquelon</option>
<option value="PN">Pitcairn</option>
<option value="PR">Puerto Rico</option>
<option value="PS">Palestinian Territory</option>
<option value="PT">Portugal</option>
<option value="PW">Palau</option>

<option value="PY">Paraguay</option>
<option value="QA">Qatar</option>
<option value="RE">Reunion</option>
<option value="RO">Romania</option>
<option value="RS">Serbia</option>
<option value="RU">Russia</option>
<option value="RW">Rwanda</option>
<option value="SA">Saudi Arabia</option>
<option value="SB">Solomon Islands</option>

<option value="SC">Seychelles</option>
<option value="SD">Sudan</option>
<option value="SE">Sweden</option>
<option value="SG">Singapore</option>
<option value="SH">Saint Helena</option>
<option value="SI">Slovenia</option>
<option value="SJ">Svalbard and Jan Mayen</option>
<option value="SK">Slovakia</option>
<option value="SL">Sierra Leone</option>

<option value="SM">San Marino</option>
<option value="SN">Senegal</option>
<option value="SO">Somalia</option>
<option value="SR">Suriname</option>
<option value="ST">Sao Tome and Principe</option>
<option value="SV">El Salvador</option>
<option value="SY">Syria</option>
<option value="SZ">Swaziland</option>
<option value="TC">Turks and Caicos Islands</option>

<option value="TD">Chad</option>
<option value="TF">French Southern Territories</option>
<option value="TG">Togo</option>
<option value="TH">Thailand</option>
<option value="TJ">Tajikistan</option>
<option value="TK">Tokelau</option>
<option value="TL">East Timor</option>
<option value="TM">Turkmenistan</option>
<option value="TN">Tunisia</option>

<option value="TO">Tonga</option>
<option value="TR">Turkey</option>
<option value="TT">Trinidad and Tobago</option>
<option value="TV">Tuvalu</option>
<option value="TW">Taiwan</option>
<option value="TZ">Tanzania</option>
<option value="UA">Ukraine</option>
<option value="UG">Uganda</option>
<option value="UM">United States Minor Outlying Islands</option>

<option value="US">United States</option>
<option value="UY">Uruguay</option>
<option value="UZ">Uzbekistan</option>
<option value="VA">Vatican</option>
<option value="VC">Saint Vincent and the Grenadines</option>
<option value="VE">Venezuela</option>
<option value="VG">British Virgin Islands</option>
<option value="VI">U.S. Virgin Islands</option>
<option value="VN">Vietnam</option>

<option value="VU">Vanuatu</option>
<option value="WF">Wallis and Futuna</option>
<option value="WS">Samoa</option>
<option value="XK">Kosovo</option>
<option value="YE">Yemen</option>
<option value="YT">Mayotte</option>
<option value="ZA">South Africa</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>

</select>
    </td>
   </tr>
            <tr>
    <td class="style3" style="width: 138px">State/Region/Province</td>
    <td class="required" style="width: 6px">*</td>
    <td class="sectiontableentry2"><div id="getStates"><select name="statename"><option value="">Select a country</option></select></div></td>
   </tr>
<!-- More Table Here.... -->


This is the javascript/ajax that grabs the state info:
				
var xmlhttp;

function showState(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getstate.php";
url=url+"?country="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==1)
{
document.getElementById("getStates").innerHTML= "<option selected=\"selected\">...Searching....</option><img src=\"images/spinner.gif\" />";
}
if (xmlhttp.readyState==4)
{
document.getElementById("getStates").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}


Here's 'getstate.php'
				
<?php
$country=$_GET["country"];
$request_url = "http://ws.geonames.org/countryInfo?country=" . $country;
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml_raw = curl_exec($ch);
$countryxml = simplexml_load_string($xml_raw);
echo '<select name="statename">' . "\n";
echo '<option selected="selected" value="">Select a state</option>' . "\n";
foreach ($countryxml->country as $link) {
$geonameid = $link->geonameId;
$stateurl = "http://ws.geonames.org/children?geonameId=" . $geonameid;
$statexml = simplexml_load_file($stateurl);
foreach ($statexml->geoname as $link) {
$statename = $link->name;
echo '<option value="' . $statename . '">' . $statename . '</option>' . "\n";
}
}
echo '</select>';
?>


The image 'spinner.gif' is attached....of course you can use whatever image you want, or none at all :)

I originally used the curl method to get the list of countries too, but really it took too long loading the page. It's better to just hard code the countries first, I think.

Hope this helps someone!

Attachments
spinner.gif
spinner.gif
(1.53 KiB)
12969 Downloads/Views
GreyHead

Hi billthecat,

Great example, thank you.

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

a
about2flip

Hi:

How can I start to use this. I am not sure where to begin to use the code above. Do I have to generate Country/State drop down boxes, or does it do it automatically within my developed form.

Any help is greatly appreciated.

Thanks

GreyHead

Hi about2flip,

The example here inclues a list of countries and looks up the corresponding states/regions list from the online database at geonames.org.

What exactly do you need to do in your form?

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

a
about2flip

This script works, but with complications.

I found this plugin on Joomla.org called CS Lookup that does the same thing and is very easy to install.

http://extensions.joomla.org/extensions/contacts-and-feedback/forms/14956

So if you are trying to do this with your CF's, I suggest you download CS Lookup.

n
njrpartnership

I'm looking for this effect in joomla 1.6 and am very new to Chronoforms. Basicially I'd like to have a drop list for the country and state for user to select when completing a data form. What need to to be enabled and where to insert the code will be a great help.

GreyHead

Hi njrpartnership,

I have a tutorial that you can buy here on using Ajax with ChronoForms v4. The second example is a US State + County list that could be adapted for Country + State

There's also a simpler, non-Ajax approach to a double drop-down in this extract from The ChronoForms Book. It was written for ChronoForms v3 but should be easily adaptable to ChronoForms v4.

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

GreyHead

Hi ricky75,

There isn't an example quite like that. You can fairly simply extend the double drop-down to behave like that if you need to.

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

c
codeslayer

Hi Billthecat,

Where should I put the php file "getstate.php"?

Thanks

Ronn

Put it in the root of your site

I believe in Angels....

R
Rolfo

What is the difference in using the XMLHttpRequest(), the JSONRequest.get and Request.HTML?

I build an Ajax function to automatically fill-in multiple single formfields, but I cannot parse the JSON Object result into the fields using the Request.HTML. It just states [object Object] whatever I try.

Should I then use a XMLHttpRequest instead?

Looking at the php page the result is a clean string, but back in the Javascript, it cannot be read the proper way. Even if eval is used.

I hope someone can help.
Rolf

GreyHead

Hi Rolf,

Which version of ChronoForms are you using? You can find the version from Site Admin | Extensions | Install/Uninstall | Components in Joomla! 1.5 or Site Admin | Extensions | Extension Manager | Manage in Joomla! 1.6.

Use the MooTools methods, there are examples in the MooTools docs or in this tutorial

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

R
Rolfo

Sorry not to mention that Bob, but my version is V4 in J1.7.1
I already bought the tutorial :-) which I used as startingpoint.

And in there you use the RequestHTML function which is fine when requesting for a complete html-dropdownlist. But I need multiple values to populate formfields, so I made the php produce a JSONencoded string like this {"field1":"value1","field2":"value2"} but the oncomplete function back in javascript cannot decode or get values out of the object. (via alert I can see Undefined or [object Object])

The whole 'get values of' works ok when hardcoding/declaring a var with the JSON string just in the Javascript. Therefore I thought that it might be due to the fact that the request is RequestHTML. So I am trying to build the request again with a XMLHttpRequest, to see if that makes a difference.

But I didn't crack that nut already... So i hope that someone can agree that that is the way. :roll:
bye, Rolf

GreyHead

HiRolf,

Don't have time to look right now but I though that the MooTools 1.3 code unpacked the reuslt for you into an 'r' object???? (or maybe a 'result' object?)

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

R
Rolfo

Solved! The JSON request returns a shockwave object. (can be seen when alerting like this: alert([n, theObjectyouneedtoinspect.toSource() ]); ) Therefore it is needed to refer to the response.text or response.html and parse it.

This code below delivers the returned values to the corresponding fields. It might come in handy for other people who wants to update multiple fieldvalues with Ajax.

				onSuccess: function(){
var jsondebiteur = JSON.parse(this.response.html, function (key, value) {
document.getElementById(key).value = value;
}
);
       },


Bye, Rolf

a
andyss

Putting getstates.php into a custom code box in an "ajax" event in CF4RC2.0/J!1.73 and trying to save results in a 403 Error:

				Forbidden

You don't have permission to access /administrator/index.php on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.


Just curious as to whether it's even possible to put getstates.php into a custom code box at all or what in it would throw the error?

Andy

***EDIT***
It seems any curl_* statements will throw the form off. I guess the curl actions replace curl statements in any custom code box. I'm going to try to see if using the curl actions work with this script.
BTW, I'm not a coder by any means so if Bob, Max or anyone else has *ANY* insight, it would be greatly appreciated!

***EDIT 2***
I'm totally at a loss on how to do this. I got the proper response from the geonames website (I think) through a curl_gh action, but have no idea what to do with the response.

GreyHead

Hi Andy,

How are you calling the Ajax event? What's the URL you are using?

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

a
andyss

Hi Bob, the form name is 'ajax' and the event is 'getstates'.



In Curl [GH]:




The call is made to:
				http://www.mysite.com/index.php?option=com_chronoforms&chronoform=ajax&event=getstates
				


...with the following result:



Now what to do with the result as the web page data returned from geonames doesn't seem to be in any variable in $form->data. In the getstates.php posted by billthecat, he used:

				$xml_raw = curl_exec($ch);
				


but I can't figure out where to do something similar.

Any thoughts?

Andy

Attachments
events.png
events.png
(6.23 KiB)
5920 Downloads/Views
result.png
result.png
(36.82 KiB)
5958 Downloads/Views
curl-gh.png
curl-gh.png
(19.44 KiB)
5950 Downloads/Views
GreyHead

Hi Andy,

I don't see how the cURL action helps you here? I'd expect you just to copy or include the getstates.php file into the a Custom Code action in the getstates event?

Bob

ChronoForms technical support
If you'd like to buy me a coffee or two, thank you very much

a
andyss

Hey Bob, it's more out of trying to figure out how to accomplish it than anything else. I actually do have it working calling getstates.php. I'm just trying to figure out how to parse the HTML response just for personal knowledge. On a side note, when including a chronoform in an article via the cf plugin, it seems to break the ajax functionality of this script. It works when calling the form directly.

Andy