it should look something like this:
$(function(){
$.ajax( {
url:"/listStates",
type:"GET",
success:function( data ) {
var statesList = data;
if ( typeof(data) == "string" ){
statesList = JSON.parse(data);
}
$.each( statesList, function( index, state ){
$("#state").append($("<option></option>",{value:state.value, text:state.label});
});
},
error:function( result ) {
console.log(["error getting states",result]);
}
});
$("#state").change( function(){
$.ajax({ url : "/listCities",
data : {"state": $("#state").val() },
type:'GET',
success:function( data ) {
var citiesList = data;
if ( typeof(data) == "string"){
citiesList = JSON.parse( data );
}
$("#city").empty();
$.each(citiesList, function(index,city){
$("#city").append($("<option></option>", {"value":city.value, "text":city.label}));
}
},
error:function( result ){ console.log(["error", result]); }
})
});
This might get you started, but I haven't followed the best practices here.
Pass the
- I am registering for a "change" event on select with state id.
- On change, if it was started, I make an Ajax request to the "/ listCities" address
- I am assuming this place is called with the "GET" method
- I am passing in the currently selected state, so the server will know which cities to list.
- If Ajax via error, I log the error to the console.
- If the Ajax was successful, I populate the select with the id "city" with parameters containing the values ββfor each city and a label.
I was taking the following things while writing code
- You have a GET / listCities route that expects state.
-
The response from this route is JSON containing a list of values ββand labels for each city. Something like that:
[{ value : "AM" , label : "Amsterdam" }, .... ]
The only thing you might need to read for this example is:
If you have any questions, please comment on my answer, I will be happy to explain / add / change
source
to share