dynamic select option in codeigniter - javascript

I am creating dependable select option in codeigniter. To populate first option was easy but i am bit troubling in displaying the second option and third option. Need help on this
My database contain:
In head table:
h_id, head fields,
subhead table
h_id, sh_id, subhead fields and
points table
sh_id, points_name fields
controller
class Mobile extends App_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper(array('url','language','form'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
$this->lang->load('auth');
$this->load->model('mobiles_model');
}
function index()
{
if (!$this->data['logged_in'])
{
redirect('auth/login','refresh');
}
$rows = $this->mobiles_model->get_users_devices();
if ($rows)
{
$this->data['devices_list'] = $rows;
}
$this->_render_page('trackall', $this->data);
}
function _render_page($view, $data=null, $render=false)
{
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $render);
if (!$render) return $view_html;
}
}
modal
public function get_users_devices()
{
$this->db->select('A.h_id as id,A.head');
$this->db->from($this->table_head.' as A');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
return FALSE;
}
view
<select id="head" name="head" class="form-control input-sm" onchange = "calljavascriptfunction();">
<option value="default">--Select--</option>
<?php if(isset($devices_list))
foreach ($devices_list as $value) { ?>
<option value="<?php echo $value['h_id'] ?>"><?php echo $value['head'] ?></option>
<?php } ?>
</select>
<select id="subhead" name="subhead" class="form-control input-sm">
<option value="default">--Select--</option>
</select>
<select id="points" name="points" class="form-control input-sm">
<option value="default">--Select--</option>
</select>
I have to populate the other depending on what i select. i tried several methods but none of them worked.
Thanks for help i am really stuck in this.

Suppose your you had following views loaded in HTML and you need to fetch value depending on first dropdown #head.
view code :
<select id="head">
<option id="1"> Mobile </option>
<option id="2"> Tabs </option>
<option id="3"> Laptops </option>
</select>
<select id="subhead">
</select>
jquery ajax
$("#head").change(function(){
var post_url = '<?php echo base_url() ?>mobile/getByDeviceId'
$.ajax({
type: "POST",
url: post_url,
data : { "hid" : $(this).val() },
success: function(response){
$.each(response, function(value, key) {
$("#subhead").append("<option id="+value.modelId+">"+value.modelName+"</option>");
})
}
});
});
controller function :
function getByDeviceId(){
$hid = $this->input->post("hid");
$modelList = $this->mobile_model->getByDeviceId($hid);
echo(json_encode($modelList));
}
model function :
function getByDeviceId($hid){
$this->db->select("modelId, modelName");
$this->db->from("models");
$this->db->where("hid", $hid);
$query = $this->db->get();
return $query->result();
}

Use jquery ajax() to do this, as ajax() do not disturb the current state of page and get the data from server and you can append it to the dropdown.
ajax() syntax:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
var1 :val1,
var2 :val2
},
success: function(response){ // response from process
// do your stuff here
}
});

Related

codeigniter how to populate second dropdown list based on the first one using codeigniter:

I have tried the following but what i need just to populate two dependent drop down (penality_type based on vehicle_type) list:
Is there some one to show me how to implement here please:
This is my Controller:
public function index()
{
$data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
$data['penality_type'] = $this->vehicle_type_model->getAllPenalityType();
$this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}
This is vehicle_type_model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class vehicle_type_model extends CI_Model {
/*
* Get All Vehicle types
*/
public function getAllVtype()
{
$result = $this->db->get('vehicle_type');
return $result->result_array();
}
public function getAllPenalityType()
{
$result = $this->db->get('penality_type');
return $result->result_array();
}
}
This is my View:
<div class="form-group">
<label for="vehicle_type_id">Vehicle Type</label>
<select name="vehicle_type_id" class="form-control vehicle_type_id">
<option value="">Select Vehicle type</option>
</select>
</div>
<div class="form-group">
<label for="penality_type_id">penality type</label>
<select name="penality_type_id" class="form-control penality_type_id">
<option value="">Select penality type</option>
</select>
</div>
What you are doing is incorrect. I assume that your penalty type is dependent on vehicle type, so you should pass vehicle_type id through ajax to the controller, then to your database and load them into the penalty type drop-down.
Please refer below code
Your index function will have just this,
public function index()
{
$data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
$this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}
Your view
<div class="form-group">
<label for="vehicle_type_id">Vehicle Type</label>
<select name="vehicle_type" class="form-control vehicle_type_id" id = "vehicle_type">
<option value="">Select Vehicle type</option>
<?php foreach($vehicle_type as $row) { ?>
<option value="<?php echo $row->vehicle_type_id ?>"><?php echo $row->vehicle_type_name; ?></option>
<?php } ?>
</select>
</div>
AJAX Code
var base_url = "<?php echo base_url; ?>";
$("#vehicle_type").change(function () {
if ($('#vehicle_type').val() != "") {
$.ajax({
url: base_url + "your_controller/get_penality_by_id",
type: 'POST',
cache: false,
data: {
'vehicle_type_id': $('#vehicle_type').val()
},
success: function (data) {
if($data){
$("#penality_type").html(data);
}
}
});
}
});
Controller
public function get_penality_by_id(){
$vehicle_type_id = $this->input->post('vehicle_type_id');
$data = array('vehicle_type_id' => $vehicle_type_id);
$result = $this->your_model_name->get_penality($data);
if($result){
$option = "<option value=''>--Select an Option--</option>";
foreach ($result as $row){
$option .= "<option value='".$row->penality_id."'>".$row->penality_name."</option>";
}
echo $option;
}else{
echo $option = "<option value=''>--Select an Option--</option>";
}
}
Model
public function get_penality($data){
$this->db->select('*');
$this->db->from('table-name');
$this->db->where($data);
$result_set = $this->db->get();
if($result_set->num_rows() > 0){
return $result_set->result();
}
else {
return FALSE;
}
}
Please note that your vehicle type drop-down option will have the vehicle_type id, which can be used for fetching your dependent penalty. Hope this can help you.

How to populate a dropdown with AJAX

I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js

Can't display element although it loaded?

I have problem is when i use ajax to send data to php server and get it to display in view, but data can't display in view although it loaded when i check in console. Please help me solved it.
This is my code :
View and script
<div class="col-xs-12" style="display: block; margin-bottom: 10px;">
<h5 class="col-sm-3 col-sm-offset-1 control-label" style="">Vị trí:</h5>
<div id="positionDiv" class="col-sm-3">
<select id="position" tabindex="9" name="recruitment[positions]" value="<?php echo $this->data['recruitment']->positions; ?>" data-none-selected-text class="selectpicker">
<option style="display: none" selected disabled value=""></option>
<?php foreach($this->data['position'] as $key => $value): ?>
<option value="<?php echo $value->positions ?>" <?php if ($this->data["recruitment"]->positions == $value->name): ?>selected<?php endif ?>>
<?php echo $value->name; ?>
</option>
<?php endforeach ?>
</select>
<input id="positionHidden" type="hidden">
</div>
<script>
$(document).ready(function() {
$("#position option").each(function(){
$(this).siblings("[value='"+ this.value+"']").remove();
});
$('#market').on('change', function(event) {
var value = $('#market').val();
$.ajax({
url: window.location.href,
type: 'POST',
data: {
market: value
},
success: function(response){
var indexStart = response.indexOf('id="position"') - 8;
var indexEnd = response.indexOf('positionHidden') - 49;
var str = response.substring(indexStart,indexEnd).replace(/\s\s+/g, ' ');
$('#position').remove();
$('#positionDiv').append(str);
//document.getElementById('positionDiv').innerHTML = str;
console.log($('#positionDiv'));
}
});
});
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.async = true;
});
});
</script>
Controller
class CandidateController extends BaseController {
public function __construct($route, $urlValue) {
parent::__construct($route, $urlValue);
}
public function initData() {
$this->view->setData("resource", ResourceCompany::getAllResource());
$this->view->setData("market", Market::getAllMarket());
}
public function showPosition() {
$market = $_POST['market'];
isset($market) ? $market : null;
$this->view->setData("position", Recruitment::getPositionByMarket($market));
}
public function showTitle() {
isset($market) ? $market : null;
isset($position) ? $position : null;
$this->view->setData("title", Recruitment::getTitleByMarketPosition($market, $position));
}
public function register() {
$this->initData();
if (isset($_POST['market'])) {
$this->showPosition();
}
}
$this->view->output("menu");
}
Everything alright, data send and get is okay but it can't display in view although i can get it from console.log.
mybe you have special characters in your content.
you most replace this characters before send in php code and reverse after get in javascript
"&" = & amp;
"\"" = & quot;
"'" = & apos;
"<" = & lt;
">" = & gt;
remove space after & plase

Choosing an option from select and then show data on another select box using Codeigniter

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.
<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>
And, 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?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<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>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my 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>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.

Bind on change event to a <select> populated by ajax request

I have in my projects two elements, the first one have a change listener that populates the second one like this.
<select id="user_id" style="width: 100%;">
<option value=""></option>
<?php foreach ($clients as $client) : ?>
<option value="<?php echo $client['Client']['id'] ?>"><?php echo $client['Client']['name'] ?></option>
<?php endforeach; ?>
</select>
<select id="pet_id" style="width: 100%;" disabled>
<option value=""></option>
</select>
--
$('#user_id').change(function() {
var client = {
client_id: $(this).val()
};
$.ajax({
type: "POST",
url: "<?php echo Router::url(array ('controller' => 'grooming', 'action' => 'getClientById')); ?>",
data: client,
success: function(data)
{
var json = JSON.parse(data);
if (json.result === "success") {
$('#pet_id').select2('data', null);
$('#pet_id').empty();
$.each(json.list, function()
{
$('#pet_id').append($("<option/>").val(this.breed_id).text(this.name));
});
if(!$('#pet_id').is(':enabled')){
$('#pet_id').removeAttr('disabled');
}
}
else
{
$('#pet_id').attr('disabled', 'disabled');
$('#pet_id').select2('data', null);
$('#pet_id').empty();
}
}
});
});
Now I have to add another change listener to the second selector (#pet_id) but it is not working any of these alternatives.
$('#pet_id').on('change',function (){
alert('finally worked :)');
});
$('#pet_id').bind('change',function (){
alert('finally worked :)');
});
¿What I'm doing wrong?
Thanks in advance.

Categories

Resources