Wednesday, 20 June 2012

PHP and JQuery

Using PHP and JQuery to Reterieve city wise list when selected country-script

we need to Three Files
1)Jquery.min.js which can be found at (http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js)
2)index.html
3)get_cities.php


get_cities.php



//get_cities.php
<?php
switch($_REQUEST['country']){
case 'ie': // { ireland
$cities=array(
'Cork', 'Dublin', 'Galway', 'Limerick',
'Waterford'
);
break;
// }
case 'uk': // { United Kingdom
$cities=array(
'Bath', 'Birmingham', 'Bradford',
'Brighton &amp; Hove', 'Bristol',
'Cambridge', 'Canterbury', 'Carlisle',
'Chester', 'Chichester', 'Coventry',
'Derby', 'Durham', 'Ely', 'Exeter',
'Gloucester', 'Hereford', 'Kingston upon Hull',
/* and on and on! */
'Newport', 'St David\'s', 'Swansea'
);
/**add another case with array of values(cities) to be retrieved*
eg:- for 'us'
step1) make sure that you have added and option in index.html as
<option value="us">united states</option>
now here in get_cities.php
add
case 'us':
$cities=array('texas','abc', 'bef', 'hef', 'etc');
**/
break;
// }
default: // { else
$cities=false;
// }
}
if(!$cities)echo 'please choose a country first';
else echo '<select name="city"><option>',
join('</option><option>',$cities),
'</select>';
print_r($_REQUEST);
?>





index.html

<html>
<head>

<!-- 1) use this if yu want to include js script from google api
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js </script>
1)ends here (OR)-->

<!--use this if you have downloaded the JavaScript code
<script src="jquery.min.js"></script>
2) ends here-->

<script>

function setup_country_change(){

// If #country is changed, then it calls update_cities() function

$('#country').change(update_cities);

}

function update_cities(){

var country=$('#country').attr('value');

// Calls get_cities.php and when retrieved, call show_cities() with the result.

$.get('get_cities.php?country='+country, show_cities);

}

function show_cities(res){
// Replace contents of #cities with retrieved result
$('#cities').html(res);
}
// Run setup_country_change() when the document is ready
$(document).ready(setup_country_change);
</script>
</head>
<body>
<form>
<table>
<tr>
<th>Country</th>
<td>
<select name="country" id="country">
<option value=""> -- please choose -- </option>
<option value="ie">Ireland</option>
<option value="uk">Great Britain</option>
<!--add another <option>to diaplay another country</option>-->
</select>
</td>
</tr>
<tr>
<th>cities</th>
<td id="cities">please select a country first</td>
</tr>
</table>
</form>
</body>
</html>

No comments:

Post a Comment

Search Engine Submission - AddMe