Currently I have a select option where I'm running a forloop to fetch all the records from the database like so:
<?php if($cities) foreach($cities as $cit): ?>
<option value="<?php echo $cit['id']; ?>" <?php echo ($listing[0]['emirate'] == $cit['id'])?'selected="selected"':''?>><?php echo $cit['name']; ?></option>
<?php endforeach; ?>
Now this fetches around 30000 entries from my database which slows down my page everytime it is loaded in because it adds an extra 30000 lines of code. So I want a way to call this through a AJAX request that loads another view with the same forloop. To do this I tried creating a new file named ajaxcities.php and placed the following code:
<select name="emirate" class="form-control select2 selectsearch" <?php echo (isset($read) ? $read:''); ?> required>
<option value="<?php echo set_value('country'); ?>">Select City</option>
<?php if($cities) foreach($cities as $cit): ?>
<option value="<?php echo $cit['id']; ?>" <?php echo ($listing[0]['emirate'] == $cit['id'])?'selected="selected"':''?>><?php echo $cit['name']; ?></option>
<?php endforeach; ?>
</select>
Then I replaced this code where it was previously in my view class before to this:
<label class="control-labels ">City</label>
<span id="city-wrap">
<div class="invalid-feedback">Please choose a City</div>
<script>
function getcity(obj){
var dataString = new Object();
dataString.type = obj.val();
$.ajax({
type: "post",
url: "<?php echo site_url('listings/ajaxgetcity'); ?>/",
data: dataString,
success: function(result) {
$('#city-wrap').html(result);
}
});
}
</script>
And made a new controller with the following:
public function ajaxgetcity()
{
$views['cities'] = $this->listings_model->cities();
$this->load->view('crm/listings/ajaxcities',$views,false);
}
But this removed the select dropbox altogether. I want a way to load this only with an AJAX call and not everytime the page is reloaded
Related
Currently I have 2 select boxes called Country and City. Now I've made it so that the city data is populated according to the value selected in country using AJAX. To do this I've used the following code:
edit.php:
<select name="country" onchange="getcities($(this).val())" required>
<option value="<?php echo set_value('country'); ?>">Select Country</option>
<?php if($countries) foreach($countries as $country): ?>
<option value="<?php echo $country['id']; ?>" <?php echo ($listing[0]['country'] == $country['id'])?'selected="selected"':''?>><?php echo $country['name']; ?></option>
<?php endforeach; ?>
</select>
<label class="control-labels ">City</label>
<div id="emiratewrap">
<select name="emirate" id="emirate">
<option value="">Select City</option>
</select>
AJAX
$(document).ready(function () {
getcities($('#country').val());
});
function getcities(obj){
console.log(obj);
var dataString = new Object();
dataString.emirate = '<?php echo $property->emirate ?>';
$.ajax({
type: "get",
dataType:"json",
url: "<?php echo site_url('listings/ajaxgetcitiesedit'); ?>/"+obj,
data: dataString,
success: function(e) { $('#emiratewrap').html(e.result);
$bb = "<?php echo $property->status; ?>";
if($bb=="Y") {$("#emiratewrap select").addClass("disabled"); }
}
});
}
Controller:
function ajaxgetcitiesedit($country=''){
$emirate = $this->input->get('emirate');
if(!$country) return false;
$cities = $this->listings_model->get_activepair_cities(array('country_id'=>$country),'*','name asc');
$html = '<select name="emirate" id="emirate" class="form-control select2 required" onchange="oemirate(this);">';
$html .= ($emirate <1)? '<option value="">Select Emirate</option>':'';
foreach($cities as $city):
$html .= '<option value="'.$city['id'].'" '.($city['id'] == $emirate ? 'selected="selected"' : '').'>'.$city['name'].'</option>';
endforeach;
$html .= '<option value="Other">Other</option> </select><input type="text" id="other_emirate" name="other_emirate" class="form-control" style="display: none;" />';
echo json_encode(array('result'=>$html));
}
Now currently I'm working on edit page where it should initially show what value the user had selected while adding the entry. As of now the functionality of the second select works fine as intended as it changes its options when the 1st select data is changed and also gives the correct value in database when update is pressed.
Now the only problem here I have is that initially when loading into the page, it doesn't show anything in the second select box even though there is a value for it in the database. I performed a console.log(obj); in getcities(obj) and initially it returned undefined and everytime I change country, it gives a value in my log.
I would like when I select the cats option that only the breed of cats appears, such as the Siamese example. If I select dog, I only want to get the breed of dogs, such as Pitbull and others.
Can you help me with the code, it tells me to use jquery, but how is it done I am just learning?
<div class="form-group">
<div class="row">
<div class="col-12 col-sm-6">
<label for="especie">Especie</label>
<select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
<option value="">Seleccionar especie</option>
<?php foreach ($especie as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<option value="">Seleccionar raza</option>
<?php foreach ($raza as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
</div>
</div>
According to your Question you want Dynamic dependant drop down list in codeigniter with ajax / jQuery.
PHP VIEW :
<div class="col-12 col-sm-6">
<label for="especie">Especie</label>
<select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
<option value="">Seleccionar especie</option>
<?php foreach ($especie as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<!-- Data here will be auto populated by ajax -->
</select>
</div>
Controller :
public function get_data()
{
$id_especie = $this->input->post("id_especie");
$SUbCatdata = $this->db->get_where('tableName',array('id'=>$id_especie))->result_array();
$option ="<option selected disabled value=''>Select Name</option>";
foreach($SUbCatdata as $row)
{
$option.="<option value='".$row['id']."'>".$row['nombre']."</option>";
}
echo $option;
}
jQuery / Ajax :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#id_especie").on("change",function(){
var id_especie = $(this).val();
$.ajax({
url : "<?php echo base_url('Controller/get_data') ?>",
type: "post",
data: {"id_especie":id_especie},
success : function(data){
//alert(data);
$("#id_raza").html(data);
}
});
});
</script>
Note : For more info regarding change()
https://api.jquery.com/change
If I understand you correctly, you want to create a sub-dropdown list that is dependent on the selection of another (main) dropdown list. If this is the case, here's what you need to do.
First, you need to create a file that contains code that will fetch results based on what is supplied. That is (in your example), if the main category is "dogs", it will query the database for all "species" of dogs, and return the result. Something like this:
Category Controller
class Category_controller extends CI_Controller{
// Get Subcategory method
public function get_subcategory()
{
// Check if input ($_GET or $_POST) exists
if ( $this->input->post_get() )
{
$main_cat_id = $this->input->post_get('mainid'); // main category id
// Perform your db query here to get the subcategory of the main cat
// Echo the result after performing a foreach loop like you did in the
// html file. <option value="value_id">value name</option>
$result = ""; // store empty value first
foreach ($dbresult as $value)
{
$result .= '<option value="$value['id']">$value['nombre']</option>';
}
echo $result;
}
}
}
SubCategory.js
$(document).ready(function() {
$('select[name="id_especie"]').on('change', function() {
var catid = $(this).val(); // will get the value attribute of the selected main category
// Perform ajax request
$.ajax({
url: 'url-to-the-subcategory-controller', // remember to set this in your config/routes.php file
method: 'POST',
cache: false,
data: {mainid: catid},
dataType: 'html',
success: function(data) {
$('select#id_raza').html(data); // update the subcategory dropdown
},
error: function(data) {
console.log(data);
}
});
})
});
So, your second select box select#id_raza show look like so in your view file:
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<option value="">Seleccionar raza</option>
<!-- Data here will be auto populated by ajax -->
</select>
</div>
I need to POST the value of the selected option to use in a query on another page.
This is my form:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="switch-area">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name'] ?>" value="<?php echo $test3['Name'] ?>"><?php echo $test3['Name'] ?></option>
<?php endwhile; ?>
</select>
<button class="btn btn-info">View Area</button>
</form>
I am using ajax and this is my code:
$(document).ready(function() {
$('select[name="switch-area"]').change(function(){
var status = $(this).val();
$.ajax({
type: 'POST',
url: 'sim-area.php',
data: {changeStatus: status}
});
});
});
Then on sim-area.php this is my code to grab the data:
$selectedArea = $_POST['switch-area'];
But I keep getting an undefined index error, am I posting this in the correct way?
You're sending changeStatus but not switch-area in your data, you want
$selectedArea = $_POST['changeStatus'];
I am banging my head against a wall with this now so any help will go a long way with this one.
I am trying to get some data from a drop down list and update a database with the data selected.
This is my drop down list:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status[]">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
View Area
This is my ajax:
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: status},
success: function() {
"area switched"
}
});
});
and this is my page that is updating the databse (sim-area.php):
<?php
$userID = $user['userID'];
$selectedArea = $_GET['changeStatus'];
$queryAreaName = "
SELECT UserID, Name, U_NB, U_RTN
FROM Table
WHERE UserID = '$userID' AND Name = '$selectedArea'";
$getAreaname = sqlsrv_query($sapconn2, $queryAreaName);
$areaSwitch = sqlsrv_fetch_array($getAreaname, SQLSRV_FETCH_ASSOC);
$areaNB = $test2['U_NB'];
$areaRTN = $test2['U_RTN'];
//UPDATE TABLE
?>
No matter what I try I get an undefined error, I have changed it to hard code the values and in inserts fine, so I know everything is working fine, It just isn't passing the data through
Looks you are not passing data correctly to ajax call.
Below is updated code for dropdown (changed name of select and added id attribute):
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status" id="changeStatus">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
Updated code for jquery (changed code for passing value of data):
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: $('#changeStatus').val()},
success: function() {
"area switched"
}
});
});
I am unable to post values from multi select drop down. Actual problem is in the edit profile part of user in this section i am not able to post values of already selected values from database.
This is my html part
<select name="drop_caste[]" id="cast_to" class="form-control new-two" size="8" multiple="multiple">
<?php foreach($selectedcast->result() as $row): ?>
<option value="<?php echo $row->cid; ?>" ><?php echo $row->caste ; ?></option>
<?php endforeach; ?> </select>
</select>
This is the code i am using to post the value
$this->input->post('drop_caste');
You need to add drop_caste into an array as
$data['drop_caste'] = $this->input->post('drop_caste');
print_r($data);// here you get your value
OR you can use foreach loop for it
foreach($this->input->post("drop_caste") as $drop_caste){
echo $drop_caste;
}
OR you can direct change POST array in to string
$caste = implode(',',$this->input->post("caste"));
JS:
Trigger this on some action:
var config = { learn : [] };
$('#learn_multiselect option:selected').map(function(a, item){
config.learn.push( { "id" : item.value } );
});
//write code for ajax to send this config object using ajax to your controller
//something like this
$.ajax({
url: $url,
method: $method,
data: $dataArr,
dataType: $dataType,
contentType: $contentType
}).done(function(data){
//handle as required
}).fail(function(data){
//handle as required
});
HTML:
<select id="learn_multiselect" multiple="multiple">
<option value="1">Science</option>
<option value="2">Maths</option>
</select>
Now you should be able to get the POSTED(or what ever method you used in AJAX) data in your controller.