Reputation: 1093
The selected radio button will show its corresponding list of cities by a dropdown box. For example, upon the selected radio button ‘Ontario’, a dropdown box with matching cities will show up (in this example the ‘Region’ is Ontario and the id is 77).
All PHP functions, loops and the JavaScript code mentioned below in the example, are working correctly:
<script type="text/javascript">
$(document).ready(function(){
$('#locationTree input:radio').change(function() {
var buttonPressed = $('input:radio[name=Region]:checked').val();
if(buttonPressed == 77) {
var listCities = $("select[name='City']");
<?php View::newInstance()->_exportVariableToView(77); ?>
<?php while(has_list_cities()) { ?>
$("<option><?php echo list_city_name(); ?></option>").appendTo(listCities);
<?php } ?>
}
});
});
</script>
To get list of cities by different regions and not specifically to 77, I can slightly change the PHP code as follows:
<?php View::newInstance()->_exportVariableToView($regionCode); ?>
and since the variable ‘buttonPressed’ detects the selected id of ‘Region’, I can add the following simple script:
<?php $regionCode = "<script>document.write(buttonPressed)</script>"; ?>
After the above changes:
var listCities = $("select[name='City']");
<?php $regionCode = "<script>document.write(buttonPressed)</script>"; ?>
<?php View::newInstance()->_exportVariableToView($regionCode); ?>
I know PHP is run server side and JavaScript is run client side but I thought that my simple solution for exchanging variables between PHP and JavaScript should work… but it doesn’t work. I really ask someone help me get it working.
Upvotes: 1
Views: 534
Reputation:
Exchange variables (sever to client) by using the data attribute properties HTML 5 provides. I do this for initial page loads.
To exchange variables after the initial page load, one may use ajax calls.
data attribute example
HTML via PHP Write
<div id='universals' data-path='/zz/' data-load='1'></div>
JavaScript
var data_dom = $('#universals')[0],
key,
universals = [];
for (key in data_dom.dataset) {
universals[key] = data_dom.dataset[key];
}
Upvotes: 2