I’m using CakePHP 1.2.4 and I have two search filters in a search form that interact this way : a dropdownlist is populated with countries and another ddl is populated with the states of the country selected in the first ddl.
This is done with ajax
I need to call the ajax function when the page is refreshed when they’re used in a search form else the states ddl is not populated again.
These dropdownlists are also used in other types of views. For example, on an edit_address.ctp page, the selected values when opening the page would be the ones saved in the database.
However, on the edit_address.ctp page I need not to update the values on refresh (or onload), because I don’t want the states to be updated unless the user change the country manually.
$('.ajaxSelect').each(function(){
$(this).change(function(){
updateSelect($(this));
});
//call function on load only for filters in a search form
if($(this).closest('.frmSearch').length > 0){
if($(".ajaxSelect option:selected").text() != ""){
$(this).change(updateSelect($(this))).change();
}
}
})
It works fine with this function but then in edit_address.ctp, if the user change the country (without saving it) and refreshes the page, the states are reseted to match the default country BUT the country selected remains the one selected before refreshing so the states don’t match anymore with the country.
Here’s an example of the countries filter
<select id="AddressCountryId" class="ajaxSelect" linked="AddressRegionId" method="getRegion" name="data[Address][country_id]">
And the states filter
<select id="AddressRegionId" name="data[Address][region_id]">
var_dump($_POST) is empty when refreshing so I cannot access selected values this way in the address controller.
The other thing I can think of is, in the ajax function above, to check if the selected state in the view matches the country selected, by calling a method from the model. Is it the right way to go? Should I create a new function in the ajax controller to access the model function instead?
In short, I want the states list to be updated with ajax whenever the selected values do NOT come from the database (unless the user manually selects another country) if it makes sense
There might be some key concept I’m missing. Feel free to ask precisions as it may be confusing, thanks
Edit : I’m guessing this might not be a question of when to make the ajax call or not, but rather how to keep the dropdownlists values and their selected values after refresh (edited the title as well)
HTTP is stateless. So when you refresh the browser, it is a new HTTP request and it does not have any idea what was the selected item in the dropdown.
One possible workaround is to store the state in some persistent medium. Session variable ,Database are two options you can think of.