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.
Related
I am new to Ajax and JavaScript
I have a similar problem with my selects that depends on the other select but don't know where it is going wrong?
This is my Controller code- that passes the member_id to the model and it is supposed to return data back to the view selected.
public function getStates() {
$this->load->model('ReferenceModel');
$this->load->model('DailyModel');
$this->load->model('MembersModel');
$this->load->model('FundsModel');
$postData = array('member_id' => $this->request->getPost('member_id'));
$dataa = $this->FundsModel->getStates($postData);
echo json_encode($dataa);
}```
This is my AJAX Request Code
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#member_id').change(function(){
var member_id = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>Historic/getStates',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
// Remove options
$('#id').find('Select Member').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#id').append('<option value="'+dataa['id']+'">'+dataa['fund']+'</option>');
});
}
});
});
});
</script>
Model
public function getStates($postData){
$sql = 'SELECT * FROM vw_funds_summary WHERE member_id =' .$postData['member_id'] ;
$query = $this->db->query($sql);
return $query;
}```
And My HTML Codes
<select id="member_id" name="country" class="form-control">
<option>Select Member</option>
<?php
for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->member_id."'>".$fMembers->row($i)->member_name."</option>";}
?>
</select>
<select class="form-control" id="id">
<option>Select Fund</option>
</select>
What is really wrong with my Code?
I have a view of both the funds and the members, that are giving the results as shown in the attached picture.
Or is there another way to do it without having to use AJAX?
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.
I have these:
$(document).ready(function() {
getRequestCategories();
$('#requestCategory').change(function() {
getRequestDescriptions( $(this).val() );
});
});
function getRequestCategories() {
$.ajax({
url: 'getCategories.php',
dataType: 'json'
})
.done(function(categoryInfo) {
$(categoryInfo).each(function(i, category) {
$('<option>').val(category.RequestCategoryDisplay).text(category.RequestCategoryDisplay).appendTo( $('#requestCategory') );
})
});
}
function getRequestDescriptions(requestCategory) {
$.ajax({
url: 'getDescriptions.php',
dataType: 'json',
data: { requestCategory: requestCategory }
})
.done(function(descriptionInfo) {
$(descriptionInfo).each(function(i, description) {
$('<option>').val(description.RequestDescriptionDisplay).text(description.RequestDescriptionDisplay).appendTo( $('#description') );
})
});
}
Category
<select name="requestCategory" id="Category" style="width:250px;font-size:10pt;" class="changeable" data-summary="summCategory">
<option value=""></option>
</select>
Description
<select name="description" id="description" style="width:250px;font-size:10pt;" class="changeable" data-summary="summSubCategory">
<option value=""></option>
</select>
How it works currently:
When you select a value from the Category dropdown, all the values associated with your selection are automatically into the description dropdown.
This works fine.
However, we have a new requirement to populate the following hidden form field with user's selection from the description dropdown:
<input name="RequestID" id="RequestID" type="text" width="300" value="" class="changeable" />
In other words, once the description dropdown is populated with values based on selection from Category dropdown, then when a user selects one of the values from the description dropdown, the accompanying value of RequestID should be saved into a hidden form field.
I tried modifying the getDescriptions function but I am not getting the correct values.
Each value I select from the description dropdown gives me same values for RequestID.
Can you please see what I am doing wrong?
Thanks so much in advance.
function getDescriptions(requestCategory) {
$.ajax({
url: 'getDescriptions.php',
dataType: 'json',
data: { requestCategory: requestCategory }
})
.done(function(descriptionInfo) {
// get number of items in array given by php
var Desc_count = descriptionInfo.length;
// loop request descriptions
for (var i = 0; i < Desc_count; i += 1) {
// append an <option> tag to your <select>
$('#description').append('<option value="' + descriptionInfo[i].RequestID + '">' + descriptionInfo[i].RequestDescriptionDisplay + '</option>');
}
// Listen for the value of the <select> to change
$('#description').on('change', function () {
// get the value of the selected option ,the value is the descriptionInfo[i].RequestID
var value = $( "#description option:selected").val();
// Set the value of the hidden fields based on the <select>'s ID choosing the corret array element
$('input[name="RequestID"]').val(value);
});
});
}
Very strange this isnt working.. is your on change event happening in $(document).ready() ?
I try to help:
instad of your $('#description').on('change', function () { event try this:
$(document).ready(function() {
$('#description').change(function() {
$('#RequestID').val($(this).val());
});
});
if this doesnt work try:
$(document).ready(function() {
$('#description').live('change', function() {
$('#RequestID').val($(this).val());
});
});
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);
}
I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});