Reputation: 13
I need in my project to load some html from external file like you see in below code this my php code
if(strtolower($_SERVER["request_method"]) == "get") {
$html = "";
$path = $_GET["path"];
if($path == "cities-select-options") {
$country_code = htmlspecialchars($_GET["country_code"]);
$get_cities = get_cities($country_code);
$html .= ' <option value=""> --- </option> ';
foreach($get_cities as $city):
$html .= ' <option value="">'.$city["city_name"].'</option> ';
endforeach;
echo $html;
}elseif() {
/* */
}
}
and this my js code
$( "#ad_country" ).on("change",function() {
$country_id = $(this).val();
$.get("htmlLoader.php?path=cities-select-option&country_id="+$country_id,function(html) {
$("#ad_city").html(html);
});
});
but I'm confused by this method. because I have too many section need to be load via ajax. So my question is : there is way to do that without writing many if conditions ?
Upvotes: 1
Views: 63
Reputation: 780974
You can put the code for each path in different functions, and use an associative array to call them.
$paths = array(
'cities-select-option' => 'get_cities_options',
'states-select-option' => 'get_states_options',
...
);
function get_cities_options() {
$html = ' <option value=""> --- </option> ';
$country_code = $_GET["country_code"];
$get_cities = get_cities($country_code);
foreach($get_cities as $city):
$html .= ' <option value="">'.$city["city_name"].'</option> ';
endforeach;
return $html;
}
function get_states_options() {
...
}
if (strtolower($_SERVER['REQUEST_METHOD'] == 'get') {
$path = $_GET['path'];
if (isset($paths[$path])) {
echo $paths[$path]();
}
}
Upvotes: 1