I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
Another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
View
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
Controller
function showCategory() {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
}
My category table contains: category_id, category_name, brand_id.
use ajax onchange. .in your view file..
<select name="brand" class="form-control" id="brand" required onchange="brand(this.value,'divid')">
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<div id="divid">
<select name="category" class="form-control" id="category" required>
<option>Select Category</option>
</select>
</div>
<script>
function brand(id,divid)
{
$.ajax({
type: "POST",
data: "pid="+id,
url: '<?php echo base_url(); ?>receiving/showCategory ?>',
success: function(html){
$('#'+divid).html(html);
}
});
}
</script>
in your function showCategory() :
<div id="divid">
<select name="category" class="form-control" id="category" required>
$brandid = $this->input->post('pid');
//you can pass this brand id to your query and echo the category in option value//
<option>//your result //</option>
</select>
</div>
You need to concat the all values in success function like
options += '<option>'+msg.category[i].category_name+'</option'>;
$('#category').html(options);
Look like your code is correct, but need to change a little bit in ajax request.
You need to parse the data return into parseJson first. The options variable in for loop should concatenate with += code. See example below:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var data = $.parseJSON(msg),options;
for(var i = 0; i<data.length; i++) {
options += '<option>'+data.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
In case you have a problem with this code, you should change variable in codeigniter part for the variable that hold the results. You can see my working code below as an example :
Js Code
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>controller/function_name',
dateType : 'json',
data : {depart_id : _depart_id.val()},
success : function(data){
var json_data = $.parseJSON(data),
options;
for(var i = 0; i<json_data.length; i++){
options += '<option value="'+json_data[i].destination_id+'">'+json_data[i].location+'</option>';
}
_destination_id.html(options);
}
});
Here is codeigniter code(php)
$destination = $this->custom_model->get_destination_distinct($table,$where);
echo json_encode($destination);
Related
I want to make a dynamic dropdown using selectpicker bootstrap library, codeigniter 4, and AJAX.
I got a problem when I trigger to select the first dropdown, the second dropdown's option appended at third times select. Here I provide the video :
https://youtu.be/AVUBlhajZ_k
Here is my code:
MODEL :
function barangBySupp($namaSupp)
{
$supp = $namaSupp;
$data = $this->db->query("SELECT * FROM tablebarang WHERE supplier='$supp'");
$result = $data->getResultObject();
return $result;
}
CONTROLLER :
public function post()
{
$request = service('request');
if ($request->isAJAX()) {
$namaSupp = $request->getVar('id');
$data = $this->barangMasukModel->barangBySupp($namaSupp);
echo json_encode($data);
}
}
JAVASCRIPT
$("#selectOptSupp").on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue){
const id = $('#selectOptSupp option:selected').data('nama');
const alamat = $('#selectOptSupp option:selected').data('alamat');
const noTelp = $('#selectOptSupp option:selected').data('notelp');
$('[name=namaSupp]').val(id);
$('[name=alamatSupp]').val(alamat);
$('[name=noTelp]').val(noTelp);
$.ajax({
type: "post",
url: "/BarangMasuk/post",
dataType: "JSON",
data: {
id: id
},
cache: false,
success: function(response) {
$.each(response, function(index, data){
$('#selBarang').append('<option data-nama="'+data['namaBarang']+'" data-harga="'+data['harga']+'" data-unit="'+data['unit']+'" value="'+data['namaBarang']+'" data-tokens="'+data['namaBarang']+'">'+data['namaBarang']+'</option>').selectpicker("refresh");
});
SHORT VIEW CODE :
<select id="selectOptSupp" class="form-control selectpicker" data-live-search="true">
<?php foreach ($supplier as $value) : ?>
<option data-nama="<?= $value['namaSupp']; ?>" data-notelp="<?= $value['noTelpSupp']; ?>" data-alamat="<?= $value['alamatSupp']; ?>" data-tokens="<?= $value['namaSupp'] ?>" name="" value="<?= $value['namaSupp'] ?>"><?= $value['namaSupp'] ?>
</option>
<?php endforeach; ?>
</select>
<select id="selBarang" class="form-control selectpicker" data-live-search="true">
// OPTION DATA SHOULD APPEND HERE WHEN #selectOptSupp fires
</select>
How can I insert an Ajax result into an input value?
HTML/PHP
<select id="getcategory" name='categoryname' ><option>SELECT---</option>
<?php
$getcat = mysqli_query($con,"SELECT * FROM category ORDER BY categoryname ASC");
while($rec = mysqli_fetch_assoc($getcat)) { ?>
<option><?php echo $rec['categoryname']; ?></option><?php } ?>
</select><br>
<input class='categoryprefix' type='text' name='subcatprefix' />
Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#getcategory").change(function(){
var cprefix = $(this).val();
$.ajax({
url: 'getCategory.php',
type: 'post',
data: {categoryname: cprefix},
success: function(data) {
$(".categoryprefix").append(data);
}
});
});
});
</script>
Note:
File getCategory.php is good
I need to fill the states list on a dropdown when country is selected.
My code
view
<div class="form-group col-md-6">
<label for="inputEmail4" class="uppercase pull-left m-0">Country</label>
<!-- <input type="text" id="country" name="country" required value="<?php echo $row_all->country;?>" placeholder="Please enter your country name"> -->
<select name="country" id="country" required>
<option value="">--select country--</option>
<?php
if($countries->num_rows()>0)
{
foreach ($countries->result() as $countries_row) {
?>
<option <?php if($countries_row->id==$row_all->countryid){ echo "selected"; }?> value="<?php echo $countries_row->id;?>"><?php echo $countries_row->name;?></option>
<?php
} } ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4" class="uppercase pull-left m-0">State</label>
<select name="state" id="state" >
</select>
</div>
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#country').change(function(){
var country = $(this).val();
alert(country);
// AJAX request
$.ajax({
url:'<?php echo base_url()?>main/get_states',
method: 'post',
data: {country: country},
dataType: 'json',
success: function(response){
alert(response);
// Remove options
//$('#state').find('option').not(':first').remove();
//$('#city').find('option').not(':first').remove();
// Add options
$.each(response,function(get_states,data){
$('#state').append('<option value="'+data['id']+'">'+data['name']+'</option>');
});
}
});
});
});
</script>
controller
function get_states()
{
$this->load->helper('url');
$postData = $this->input->post();
$this->load->model('candidate_model');
$data = $this->candidate_model->fetch_states($postData);
echo json_encode($data);
}
Model
candidates_model
function fetch_states($postData)
{
//$query = $this->db->query("SELECT * FROM states");
//return $query;
$response = array();
// Select record
$this->db->select('id,name');
$this->db->where('country_id', $postData['country']);
$q = $this->db->get('states');
$response = $q->result_array();
$response= json_encode($response);
return $response;
}
Model returns value from database and it is also can be access from the view.
I alert the response and it returns array like {"id":"36","name":"delhi"}.
I need to fill this results to dropdown with id states
Any help? Thanks in advance
Try This,
Model :
function fetch_states($country)
{
$this->db->select('id,name');
$this->db->where('country_id', $country);
$q = $this->db->get('states');
if ($q->num_rows() > 0) {
return $q->result_array();
}else{
return array();
}
}
Controller :
function get_states()
{
$this->load->helper('url');
$postData = $this->input->post();
$this->load->model('candidate_model');
$country = $postData['country'];
$state = $this->candidate_model->fetch_states($country);
$respose_array['state'] = $state;
echo json_encode($response_array);
exit();
}
View ajax code :
$.ajax({
url:'<?php echo base_url()?>main/get_states',
method: 'post',
data: {country: country},
dataType: 'json',
success: function(response){
$.each(JSON.parse(response.state),function(i,item){
$('#state').append('<option value="'+item.id+'">'+item.name+'</option>');
});
}
});
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)
In my php code, I have two dropdowns which is the other one depends on the first one.
Here is the first dropdown:
<select class="form-control style" id="sel" >
<option style="color: black;" >Select...</option>
<?php foreach ($dtype as $row ) { ?>
<option style"color:black;" value="<?php echo $row['donations_type_id'];?>"> <?php echo $row['donations_type_name'];?></option>
<?php }?>
</select>
<tr>
<td>Available Donation:</td>
<td style="color: black; ">
<select name='avail' id='avail' class="form-control style" >
<option style="color:black;" value="">Select...</option>
</select>
</td>
</tr>
The second dropdown shows the data that corresponds whatever the user selects from the first dropdown.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
type: "POST",
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
success:function(data){
$("#avail").html(data);
}
});
});
});
</script>
In my controller:
public function showAvailable()
{
echo $id = $this->input->post('id', true);
$data['package'] = $this->Beneficiary_model->getDtype($id);
$output = null;
foreach ($data['package'] as $row ) {
$output.="<option value='".$row->package_id."'>".$row->package_name."</option>";
}
echo $output;
}
And in my model:
public function getDtype($id){
$this->db->select('package_id','package_name');
$this->db->from('package_table');
$this->db->where('package_type', $id);
$query = $this->db->get();
return $query->result();
}
When I tried to run the code and debug it through F12, it shows there that POST http://localhost:8999/samp/sampModule/showAvailable/2 404 (Not Found)
Why is it?
Can anyone help me with this error?
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
Take $(this) out of ajax object. It points now to ajax object itself. Try:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
**UPDATED**
Also, if the data is received from the server correctly but dropdown is still not rendered, the issue might be with the dataType property. There may be some problems with the response mime type, that cause the problem with the Intelligent Guess and data is treated as a json or xml string, so you can try to set it explicit:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
type: "POST",
dataType: 'html',
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
success:function(data){
$("#avail").html(data);
}
});
});