Dynamic Dependent Dropdown List Country and State on Code Igniter - javascript

I am working on project that uses a dynamic or dependent dropdown list on CodeIgniter. This is my noob logic, the country value from Views passed to Models, then the Models get state data with same country value from Views, then Controllers get state data from that Models and pass it again to Views. And the problem is the state dropdown list show nothing.
Sorry, iam new in coding.
//This is the Controllers (Pkl.php)
$data['all_country'] = $this->Server_Model->get_country_model();
$data['all_state'] = $this->Server_Model->get_state_model();
$this->load->view('contents/page_dashboard', $data);
//This is the Models (Server_Model.php)
function get_country_model(){
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("country");
$que = $db_jarlap->get();
return $que->result();
}
function get_state_model(){
$kakakoko = filter_input(INPUT_POST, 'country_id');
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("state");
$db_jarlap->where(" id_country = $kakakoko ");
$que = $db_jarlap->get();
return $que->result();
}
//This is the Views Content (page_dashboard.php)
<script src="<?php echo base_url() ?>resources/js/jquery-3.3.1.min.js"</script>
<script>
$(document).ready(function(){
$('#formCountry').change(function(){
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ? >application/models/Server_Model.php",
method: "POST",
data: {country_id:country_id},
success: function(data) {
$('#formState').html(data);
}
});
});
});
</script>
<select name="formCountry" id="formCountry">
<?php foreach($all_country as $semua_country): ?>
<option value="<?php echo $semua_country->id_country; ?>"><?php echo $semua_country->nama_country; ?></option>
<?php endforeach; ?>
</select>
<select name="formState" id="formState" >
<?php foreach($all_state as $semua_state): ?>
<option value="<?php echo $semua_state->id_state; ?>"><?php echo $semua_state->nama_state; ?></option>
<?php endforeach; ?>
</select>
Thanks for your help.

You should not directly call model, instead call the Pkl controller, I'm assuming that you are using the index() method on Pkl controller :
$(document).ready(function () {
$('#formCountry').change(function () {
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ?>pkl", // using Pkl controller
method: "POST",
data: {
country_id: country_id
},
success: function (data) {
$('#formState').html(''); // empty the select option element
$.each(data, function(){ // format each option returned from Pkl controller
$("#formState").append('<option value="'+ this.id_state +'">'+ this.nama_state +'</option>');
});
}
});
});
});

Related

Jquery is not spotting that a form select has changed

I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
The issue was the jquery. The code should be the following:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
alert(data);
}
});
});
});`

change event not triggered from dynamic selection

Let me put this as simple as possible. I have a ajax call which loads the dropdown dynamically. I have another ajax call which is used to display details when any item is clicked.
Problem: I cant trigger the event of second ajax call.
If second ajax call is working it has to atleast display triggered when the change event happens. But the change event not even triggers.
Code:
First ajax call
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
Continued 2nd ajax call with closing php..
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$("#name").on('change',function (e) {
var name1 = this.value;
$.ajax ({
data:{name1: name1},
type: 'POST',
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
});
</script>
<?php } ?>
output from dataprod.php
dataprod.php for reference
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<?php
$name1 = $_POST['name1'];
echo $name1;
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
echo 'triggered';
?>

How to load a template dynamically in CKEDITOR by using ajax?

I have a database table for my saved template. All are in HTML format and I want to get a specific template using an AJAX.
Here's my code:
HTML part
<div class="form-group">
<label>Select Template: <span class="text-info">(*Optional)</span></label>
<select class="form-control" name="load_template" id="load-template">
<?php if(count($templates) > 0) { ?>
<option value="">-- load template --</option>
<?php foreach($templates as $temp) { ?>
<option value="<?php echo $temp['id']; ?>"><?php echo $temp['template_name']; ?></option>
<?php } ?>
<?php } else { ?>
<option value="">There are no saved templates</option>
<?php } ?>
</select>
</div>
JS part
$('#editor').ckeditor();
$('#load-template').on('change', function(){
var id = $(this).val();
//do some ajax to get content...
console.log(id);
$.ajax({
url: "<?php echo site_url('users/user/getLoadTemplate'); ?>",
data: {template_id: id},
dataType: 'html',
type: 'post',
beforeSend: function() {},
success: function(template) {
$('#editor').html(template);
console.log(template); //ok it shows the HTML but how can I load it in my ckeditor?
},
error: function() {
alert('Unable to load template. Error in AJAX');
}
});
});
PHP side
public function getLoadTemplate() {
$type = $this->input->post('template_id');
$get_template = $this->Users_model->getLoadTemplate($type);
echo $get_template['template'];
}
How can I load my ajax response HTML in the CKEDITOR?
Instead of this
$('#editor').html(template);
Try this
CKEDITOR.instances['editor'].insertHtml(template)
or
CKEDITOR.instances.editor.insertHtml(template)

Codeigniter : Passing ajax based data

I am fetching cities data based on the onchange() event against selected country.
I have to populate cities data based on country selected.
class ajax extends CI_Controller {
public function getcities(){
if($this->input->post('countryId')){
$countryId= $this->input->post('countryId');
}
foreach ($this->user_model->getselectedcity($this->input->post('countryId')) as $key => $value) {
$cities[] = $value->city;
}
echo json_encode($cities);
}
}
In my view I have this script:
<script type="text/javascript">
$(document).ready(function (){
$('#changecountry').change(function(){
//alert($(this).val());
$.ajax({
method: "POST",
url: "<?php echo base_url()?>index.php/ajax/getcities",
data:{countryId:$(this).val()},
success: function(data){
console.log(data);
}
});
});
});
</script>
These are my dropdowns:
<?php
if($value['type']=='countryname'){
if(isset($value['countryname'])){
echo '<div class="form-group">';
echo form_dropdown('countryname', $value['options'],'','class="form-control" id="changecountry"');
echo '</div>';
}
}
if($value['type']=='cityname'){
if(isset($value['cityname'])){
echo '<div class="form-group">';
echo form_dropdown('cityname',$value['options'],'','class="form-control"');
echo '</div>';
}
}
In the success function I'm getting json data, I'm not sure how to pass this to the dropdown:
["Dubai","Sharjah","Abu Dhabi","Ajman","Ras al-Khaimah","Umm al-Quwain"]
You need to append Ajax response with your City dropdown by using ID attribute like:
<script type="text/javascript">
$(document).ready(function (){
$('#changecountry').change(function(){
$.ajax({
method: "POST",
url: "<?php echo base_url()?>index.php/ajax/getcities",
data:{countryId:$(this).val()},
success: function(response){
$.each(response, function (index, value) {
$("#selectID").append("<option value='"+value+"'>" + value + "</option>");
});
}
});
});
});
</script>
Your Drop Down (add ID attribute here):
<?php
if($value['type']=='cityname'){
if(isset($value['cityname'])){
echo '<div class="form-group">';
echo form_dropdown('cityname',$value['options'],'','class="form-control" id="selectID"');
echo '</div>';
}
}
?>
In Controller
foreach ($this->user_model->getselectedcity($this->input->post('countryId')) as $option) {
$cities[] = '<option value="'.$option["city"].'">'.$option["city"].'</option>';
}
In AJAX
success: function(html)
{
$("#state").html(html);
}
In HTML
<select class="form-control" id="state" name="state">
<option selected="selected">--Select State--</option>
</select>

dependent dropdown in wordpress theme files

I want to create state/city dependent dropdown in wordpress. This is my js file code
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#state').change(function(){
var $location = $(this).val();
alert($location);
$.ajax({
url:'ajaxurl',
type: 'post',
data: ({action : 'getcity'}),
success: function() {
$("#district").removeAttr("disabled");
$("#district").append(results);
}
});
});
});
</script>
I have created function called getcity in function.php and add hooks and action to that function and add this js file to theme js folder and enque it in function file. I m getting empty alert ?? Anybody has any idea??
add_action('wp_head','ajaxurl');
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php')."getcity"; ?>';
</script>
this is dropdown code
<p class="half_form half_form_last">
<label for="property_country"><?php _e('State ','wpestate'); ?></label>
<select name="state" id="state" class="select-submit2">
<option value="">Select state</option>
<?php
$result=$wpdb->get_results("select distinct(state) from tblcitylist");
//$wpdb->get_results($query);
foreach($result as $row) {
$state=$row->state;
echo '<option value="">'.$state.'</option>';
}
?>
</select>
</p>
In function.php
function getcity(){
global $wpdb;
if($_POST['state'])
{
$id=$_POST['state'];
$result=$wpdb->get_results("SELECT * FROM tblcitylist WHERE
state='$id'");
//$wpdb->get_results($query);
foreach($result as $row) {
$city_name = $row-
>city_name;
$city_id = $row->city_id;
echo '<option
value="'.$city_id.'">'.$city_name.'</option>';
//echo '<option value="'.'0'.'">'.'New Phase'.'</option>';
}
}
}
add_action("wp_ajax_nopriv_getcity", "getcity");
add_action("wp_ajax_getcity", "getcity");
I have included js file as follows in functions.php
wp_enqueue_script('my_own_js',
get_template_directory_uri().'/js/my_own_js.js',array('jquery'));
I think it's better to post it as an answer. I'd delete the var ajaxurl from the functions.php and use it inside the page. Then I don't see where you pass the location to the ajax. It should look like this:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#state').on('change', function() {
var location = this.value;
alert(location);
$.ajax({
type: "POST",
url:'<?php echo admin_url('admin-ajax.php'); ?>',
data: ({'action' : 'getcity', 'location' : location }),
success: function(results) {
$("#district").removeAttr("disabled");
$("#district").append(results);
}
});
});
});
</script>
then the Dropdown should look like this
<select id="state">
<option value="state1">state1</option>
<option value="state2">state2</option>
...
</select>
And for the getcity you have to get the right $_POST:
function getcity(){
global $wpdb;
if($_POST['location']){
$id=$_POST['location'];
$result=$wpdb->get_results("SELECT * FROM tblcitylist WHERE state='$id'");
$html = '';
foreach($result as $row) {
$city_name = $row->city_name;
$city_id = $row->city_id;
$html .= '<option value="'.$city_id.'">'.$city_name.'</option>';
}
}
}
add_action("wp_ajax_nopriv_getcity", "getcity");
add_action("wp_ajax_getcity", "getcity");

Categories