I want to populate textbox values automatically from DB based on dropdown selection.....I have tried this, but after selecting dropdown the page is refreshing but the values are not populated onto textbox....need Help!!
Table
Controller:
public function isrexpense()
{
$data['query'] = $this->Isr_model->getstates();
$data['names'] = $this->Isr_model->getAllNames();
$data['query1'] = $this->Isr_model->test();
$this->load->view("header");
$this->load->view('Isr/isrexpense', $data);
$this->load->view("footer");
}
Model:
function test()
{
$this->db->select('da_hq');
$this->db->from('isr_policy_master');
$this->db->where('state', $this->input->post('state'));
$query = $this->db->get();
return $query->result();
}
View:
<select class="js-example-basic-single form-control">
<?php
foreach($names as $row)
{
echo '<option></option>';
echo '<option value="'.$row->name.'">'.$row->name.'</option>';
}
?>
</select>
<select class="state form-control" id="state" name="state">
<?php
foreach($query as $row)
{
echo '<option value="'.$row->state_code.'">'.$row->state_name.'</option>';
} ?>
</select>
<script>
$('#state').on('change', function(){
var mainselection = this.value; // get the selection value
$.ajax({
type: "POST", // method of sending data
url: "<?php echo site_url(); ?>/Isr/isrexpense",
data:'selection='+mainselection,
success: function(result)
{
$("#hqda").html(result);
}
});
});
</script>
<input id="hqda" name="hqda" class="form-control" required type="number">
Controller :
public function isrexpense()
{
$data['query'] = $this->Isr_model->getstates();
$data['names'] = $this->Isr_model->getAllNames();
$this->load->view("header");
$this->load->view('Isr/isrexpense', $data);
$this->load->view("footer");
}
public function getValFromDb()
{
$state = $this->input->post('selection');
$query1 = $this->Isr_model->test($state);
echo json_encode(array('data'=>$query1));
}
Model:
function test($state)
{
$this->db->select('da_hq');
$this->db->from('isr_policy_master');
$this->db->where('state', $state);
$query = $this->db->get();
$result = $query->result();
if(count($result)>0)
{
return $result[0]['da_hq'];
}
else
{
return '';
}
}
View :
<script>
$('#state').on('change', function(){
var mainselection = this.value; // get the selection value
$.ajax({
type: "POST", // method of sending data
url: "<?php echo site_url(); ?>/Isr/getValFromDb",
data:'selection='+mainselection,
success: function(result)
{
console.log(result); // check this in your console and if require than use JSON.parse to get value
$("#hqda").val(result.data);
}
});
});
</script>
Textboxes don't have an "innerHTML" property. If you want to set the content of a textbox, you should set its value property. In jQuery you do this using the .val() method.
Replace
$("#hqda").html(result);
with
$("#hqda").val(result);
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
and http://api.jquery.com/val/
P.S. You may also want to take a look at what your AJAX call returns - it's not clear whether it would return the content you're looking for or not - it appears to return a whole HTML view, rather than just a single value to place into a textbox.
Related
I am using Codeigniter 3.1.1. I want City option to display base on the value selected with State option. Actually the City select option does not populate automatically when State option is selected. I tried to link the latest jQuery but still, it doesn't work. Your help is highly appreciated.
MyController.php
class HomeController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function index() {
$states = $this->db->get("demo_state")->result();
$this->load->view('myform_view', array('states' => $states ));
}
public function myformAjax($stateID) {
$result = $this->db->where("state_id",$stateID)->get("demo_cities")->result();
echo json_encode($result);} }
View:
<select name="state" id="state" class="form-control" style="width:350px">
<option value="">---Select State---</option>
<?php foreach($states as $key => $value)
{
echo "<option value='".$value->id."'>".$value->name."</option>";
} ?>
</select>
<select name="city" id="city" class="form-control" style="width:350px"></select>
Ajax:
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID,
type: "POST",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
You've not specified what problem you face when you run your code or what is the output or what is the error, so, we've no way of knowing what the real issue is. However, I'm sharing a working code (an excerpt from my project) of what you want; I've also changed the values according to your needs.
This follows a different approach as AJAX expects HTML to be
returned and that HTML is formed in PHP controller rather than on success in jQuery and then simply added to the desired id.
AJAX
$(document).ready(function() {
$('#state').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/MyController/myformAjax/'+stateID, // your-controller-path
// sometimes relative path might not work try with base_url() instead or configure your .htaccess properly
type: "POST",
dataType: "html", // expecting html
success:function(data) {
$('#city').empty();
$('#city').html(data); // change innerHTML of id='city'
}
});
}else{
$('#city').empty(); // $('#city').html('');
}
});
});
Controller
public function myformAjax($stateID) {
$cities = $this->db->where("state_id",$stateID)->get("demo_cities")->result(); // get all the cities -- probably want to do this in model
$cityOpt = '<option value="">--Select City--</option>'; // first option -- to prevent first option from automatically selecting when submitting data
foreach($cities as $city)
{
$cityOpt .= '<option value="'.$city->id.'">'.$city->city_name.'</option>'; // concatenate the next value
}
echo $cityOpt;
}
See if it helps you.
I have created dynamic dependent dropdown list where I am selecting and option and sending request to the controller to fetch the data from database. I need to display the selected option name in the URL once the data will be fetched from the database. I am unable to do this and getting the same page url.
View:
<script type="text/javascript">
$(document).ready(function(){
/* Populate data to state dropdown */
$('#country').on('change',function(){
var countryID = $(this).val();
var countryName= $('#country option:selected').html();
// alert(countryName);
if(countryID){
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getDistrict'); ?>/'+countryName,
data:'country_id='+countryID,
success:function(data){
$('#state').html('<option value="">Select District</option>');
var dataObj = jQuery.parseJSON(data);
if(dataObj){
$(dataObj).each(function(){
var option = $('<option />');
option.attr('value', this.id).text(this.district_name);
$('#state').append(option);
});
}else{
$('#state').html('<option value="">District not available</option>');
}
}
});
}else{
$('#state').html('<option value="">Select state first</option>');
$('#city').html('<option value="">Select district first</option>');
}
});
Controller:
public function getDistrict(){
$states = array();
$country_id = $this->input->post('country_id');
if($country_id){
$con['conditions'] = array('state_id'=>$country_id);
$states = $this->Bank_model->getDistrictRows($con);
}
echo json_encode($states);
}
Model:
function getDistrictRows($params = array()){
$this->db->select('s.id, s.district_name');
$this->db->from($this->districtTbl.' as s');
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('s.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
//return fetched data
return $result;
}
My current URL is: http://localhost/real_estate/bank
After the request I am still getting the same URL. It's not appending the name of the selected option.
I want my URL like this: http://localhost/real_estate/bank/delhi
If I am choosing delhi from the select option
Unable to get value from database in codeigniter. I tried to fetch data based on select box value(menu_code) without refreshing page using ajax but I got result undefined.
This my controller's code : login.php
public function get_menu_rights()
{
if (isset($_POST['name']))
{
$root_id = $this->input->post('menu_root_id');
$data['res'] = $this->login_model->get_menu_check($root_id);
// print_r($data['res']);
echo json_encode($data);
//$this->load->view('pages/role_rights',$data);
}
}
Below is my model code login_model.php
public function get_menu_check($root_id)
{
$this->db->select('menu_code,menu_name');
$this->db->from('create_menu as C1');
$this->db->where('C1.menu_root_id',$root_id);
$this->db->order_by('menu_code');
return $this->db->get()->result_array();
}
This is my view code role_rights.php
<form action="<?php echo base_url('login/get_menu_rights');?>" method="post">
<?php
print"<select class=\"form-control\" name=\"menu_root_id\" onchange=\"javascript:__doPostBack();\" id=\"menu_root_id\">"; ?> <option value="select">select</option>
<?php foreach($result as $res) { ?>
<option value="<?php echo $res->menu_code; ?>">
<?php echo $res->menu_name.'-'.$res->menu_code; ?>
</option>
<?php } ?>
</select>
</form>
</div>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function __doPostBack()
{
var name = document.getElementById('menu_root_id').value;
var dataString='name='+ name;
$.ajax({
type:"post",
url:"<?php echo base_url('login/get_menu_rights'); ?>",
data:dataString,
cache:false,
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>menu_code: </b>"+id+"<b> menu_name: </b>"+vname);
}
});
return false;
}
</script>
</div>
<div id="output"></div>
Hope this will help you :
Replace
$root_id = $this->input->post('menu_root_id');
with
$root_id = $this->input->post('name');
Your controller's get_menu_rights method should be like this :
public function get_menu_rights()
{
$root_id = $this->input->post('name');
if(! empty($root_id))
{
$data = $this->login_model->get_menu_check($root_id);
// print_r($data);
echo json_encode($data);
exit;
}
}
Your ajax success function should be like this :
success: function(data)
{
var html = '';
$.each(data,function(k,v){
alert(v);
html += "<b>menu_code: </b>"+v.menu_code+"<b> menu_name: </b>"+v.menu_name
});
$('#output').html(html);
}
There are a few things I noticed
$data is an undefined array & you are settings the result array returned by the model function to it's 'res' key
dataString is not a json neither it's a js array that you are sending
since you used json_encode, you need to use JSON.parse(data) in the ajax success
if you do have the result in $data['res'], then you need to do something like this - data=JSON.parse(data)['res']; now you can get id from data[0]
I think the query return empty please try this Code.....
public function get_menu_check($root_id)
{
$data = $this->db->select('C1.menu_code,C1.menu_name')
->from('create_menu as C1')
->where('C1.menu_root_id',$root_id)
->order_by('C1.menu_code')
->get();
if($data->num_rows() >= 0)
return $data->result_array();
else
return false;
}
My $this->input->post is not working when I changed the value of a dropdown menu (it dynamically display the record from db) it does not display any data and no errors too, but it's working fine if I assign a specific value to the where syntax.
Model:
public function getData() {
$where = $this->input->post('selected_holcode');
$query = $this->db->get_where("hrms.holiday", "holcode = '$where'")->result();
return $query;
Controller:
public function getHolidaylist() {
$data['record'] = $this->holiday_settings_model->getData();
$this->load->view('maintainance/holiday_settings/holiday_list', $data);
}
ajax (to display the record upon changing the dropdown menu)
<script type="text/javascript">
var controller = 'holiday_settings';
var base_url = '<?php echo site_url(); ?>';
function load_data_ajax(type){
$.ajax({
'url' : base_url + '/' + controller + '/getHolidaylist',
'type' : 'POST',
'data' : {'type' : type},
'success' : function(data){
var container = $('#holiday');
if(data){
container.html(data);
}
}
});
}
</script>
View:
<?php echo form_open('holiday_settings/getHolidaylist') ?>
<div id="holiday"></div>
<?php echo validation_errors(); ?>
<label><strong>Year</strong></label> <label><strong>:</strong></label>
<select id="syear" onchange="load_data_ajax(1)">
<?php
for ($x=2015; $x>=2008; $x--) {?>
<option><?php echo $x;?></option>
<?php } ?>
</select></br></br>
<select name="selected_holcode" onchange="load_data_ajax(1)">
<option value="SPL">SPL</option>
<option value="LGL">LGL</option>
<option value="CMP">CMP</option>
</select></br></br>
enter code here
If you say that static value makes it work then your controller and model functions are working correctly I guess, Maybe you should try this:
onchange="load_data_ajax(1)" //instead of writing this
You should just pass the value like this:
onchange="load_data_ajax(this.value)"
Or as I see you are using JQuery, you can also do this:
<select name="selected_holcode" class="toggler" > <!-- Remove the onchange event and add a new class to the element -->
<script type="text/javascript">
$(function(){ //on page load
$(".toggler").on("change", function(){
var value_to_send = $(this).val(); //get the selectbox value here
//your ajax call goes here
});
});
</script>
im not sure but try this:
<select name="selected_holcode" onchange="load_data_ajax(this.value)">
instead of : load_data_ajax(1)
or
onchange="load_data_ajax(this.options[this.selectedIndex].value)
if your Dropdown was filled with dynamic data from DB
// EDIT
And what do you want to do if syear is changed?
since you call the same function? and you should set it like this:
for ($x=2015; $x>=2008; $x--) {
echo "<option value='$x'>$x</option>";
}
Now you can get your value to your onchange function like i already said
This is what I've got so far:
This function that returns data from the model:
function get_user2()
{
$this->load->model('my_model');
$id=$this->input->post('users1');
$users2=$this->my_model->get_relations($id);
return $users2;
}
the model function:
function get_relations($usr)
{
$this->db->where('id',$usr);
$rel=$this->db->get('relacion');
if($rel->num_rows!=0)
{
$relacion=array();
foreach ($rel->result_array() as $row)
{
$relacion[]=array(
'id'=>$row['id'],
'username1'=>$row['username1'],
'username2'=>$row['username2'],
);
}
return $relacion;
}else{
return false;
}
}
and in my view:
<select name="users1" id="drop1">
<?php
if($opciones!=false){
foreach ($opciones as $row) {
echo '<option value="'.$row['user_id'].'">'.$row['username'].'</option>';
}
}
?>
</select>
<script src="jquery.js"></script>
<script type="text/javascript">
$("#drop1").change(function(){
$.ajax({
type: "POST",
url: "example.com/CI/index.php/evaluation/get_user2",
data: "users1="+$('#drop1').val(),
success: function(){
alert('it works!');
}
});
});
</script>
I want to fill a second dropdown with the options returned by the controller function, but the ajax request doesn't do anything so I haven't even got to that part. Can someone help me spot what's wrong? I already tested the controller and model's function and they work. And could you tell me how to fill the second dropdown's options?
Thank you very much!
Well I've a very similar code in one project to get some cities depending on the island the user choose. So wen the select changes, load the cities and enables the second select. The main difference is the way you pass the data.
<script type="text/javascript">
$("#idisla").change(function(){
if($("#idisla").val()!=""){
var dato=$("#idisla").val();
$.ajax({
type:"POST",
dataType:"html",
url:base_url+"admin/centros/municipios_select",
data:"idislajs="+dato,
success:function(msg){
$("#idmunicipio").empty().removeAttr("disabled").append(msg);
callback();
}
});
}else{
$("#idmunicipio").empty().attr("disabled","disabled");
}
});
</script>
The function only looks cities from the selected islad (id)
function municipios_select()
{
//el idIsla viene dado por el value del combo islas
$isla = $this->input->post('idislajs');
$data['municipios'] = $this->municipios_model->obtenMunicipios($isla);
echo $this->load->view("site/municipios_select",$data, TRUE);
}