简体   繁体   English

Ajax与codeigniter中的选择框

[英]Ajax with select box in codeigniter

i have a form with two select box. 我有两个选择框的形式。 one is for the city and the other one for the area. 一种用于城市,另一种用于区域。

My requirement. 我的要求 When some one selects a city,The areas in the city must be captured from database and displayed in another select box. 当有人选择城市时,必须从数据库中捕获城市中的区域并显示在另一个选择框中。

i tried but, i have problem with my ajax. 我尝试过,但是我的Ajax有问题。 here is my code below. 这是我的下面的代码。

view 视图

                                    <div class="location-group">
                                    <label class="-label" for="city">
                                        Location
                                    </label>
                                    <div class="">
                                        <select id="city_select">
                                            <option value="0"> select</option>
                                            <?php foreach ($city as $cty) : ?>
                                            <option value="<?php echo $cty->city_id; ?>"><?php echo $cty->name; ?></option>
                                            <?php endforeach ?>
                                        </select>
                                    </div>
                                </div>


                                <div class="location control-group" id="area_section">
                                    <label class="control-label" for="area">
                                        Area
                                    </label>
                                    <div class="controls">
                                        <select id="area_select">
                                            <option value=""> Any</option>
                                            <?php foreach ($area as $ara) : ?>
                                            <option value="<?php echo $ara->ara_id; ?>"><?php echo $ara->name; ?></option>
                                            <?php endforeach ?>
                                        </select>
                                    </div><!-- /.controls -->
                                </div><!-- /.control-group -->

controller 控制者

function __construct() {
    parent::__construct();

  //session, url, satabase is set in auto load in the config

    $this->load->model('Home_model', 'home');
    $this->load->library('pagination');


}



function index(){
    $data['city'] =  $this->home->get_city_list();
    $data['type'] =  $this->home->get_property_type_list();
    $this->load->view('home', $data);
}


function get_area(){
    $area_id = $this->uri->segment(3);
    $areas =  $this->home->get_area_list($area_id);
    echo json_encode($areas);
}

Model 模型

function get_area_list($id){
  $array = array('city_id' => $id, 'status' => 1);
  $this->db->select('area_id, city_id, name');
  $this->db->where($array);
  $this->db->order_by("name", "asc"); 
  $this->db->from('area'); 
  $query = $this->db->get();
  $result = $query->result();
  return $result;
}

Ajax 阿贾克斯

<script type="text/javascript">
$('#area_section').hide();


    $('#city_select').on('change', function() {
     // alert( this.value ); // or $(this).val()
      if (this.value == 0) {
        $('#area_section').hide(600);
      }else{


        //$("#area_select").html(data);
            $.ajax({
                  type:"POST",
                  dataType: 'json',
                  url:"<?php echo base_url('index.php?/home/get_area/') ?>",
                  data: {area:data},
                  success: function(data) {
                    $('select#area_select').html('');
                    $.each(data, function(item) {
                        $("<option />").val(item.area_id)
                                       .text(item.name)
                                       .appendTo($('select#area_select'));
                    });
                  }
                });


        $('#area_section').show(600); 
      };



    });
</script>

once i select a city, it must get all the areas in the city from database and display it in the area_select select box. 一旦我选择了一个城市,它就必须从数据库中获取城市中的所有区域,并将其显示在area_select选择框中。

can any one please help me. 谁能帮帮我吗。 Thanks. 谢谢。

Try to change this way. 尝试改变这种方式。

Your ajax code 您的ajax代码

//keep rest of the code
 $.ajax({
              type:"POST",
              dataType: 'json',
              url:"<?php echo base_url('index.php?/home/get_area/') ?>",
              data: {area:$(this).val()},//send the selected area value

Also show the area_section inside ajax success function 同时显示ajax成功函数内的area_section

Your controller function 您的控制器功能

function get_area()
{
   $area_id = $this->input->post('area');
   $areas =  $this->home->get_area_list($area_id);
   echo json_encode($areas);
}

Hope it will solve your problem 希望它能解决您的问题

Update 更新资料
Try using your ajax update function like this 尝试像这样使用ajax更新功能

 success: function(data) {
                $('select#area_select').html('');
                for(var i=0;i<data.length;i++)
                {
                    $("<option />").val(data[i].area_id)
                                   .text(data[i].name)
                                   .appendTo($('select#area_select'));
                }
              }

Simple way to do that follow the instruction on this page 遵循此页面上的说明的简单方法


https://itsolutionstuff.com/post/codeigniter-dynamic-dependent-dropdown-using-jquery-ajax-exampleexample.html https://itsolutionstuff.com/post/codeigniter-dynamic-dependent-dropdown-using-jquery-ajax-exampleexample.html


demo_state table:

CREATE TABLE `demo_state` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

demo_cities table: demo_cities表:

CREATE TABLE `demo_cities` (
  `id` int(11) NOT NULL,
  `state_id` int(12) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password. 成功创建数据库和表之后,我们必须在Codeigniter 3应用程序中配置数据库,因此打开database.php文件并添加您的数据库名称,用户名和密码。

application/config/database.php application / config / database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$active_group = 'default';
$query_builder = TRUE;


$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Read Also: How to make simple dependent dropdown using jquery ajax in Laravel 5? 另请参阅:如何在Laravel 5中使用jquery ajax进行简单的依赖下拉? Step 3: Add Route 步骤3:新增路线

In this step you have to add two new routes in our route file. 在此步骤中,您必须在我们的路线文件中添加两条新路线。 We will manage layout and another route for ajax, so let's put route as bellow code: 我们将管理ajax的布局和另一条路线,因此让我们将路线作为以下代码:

application/config/routes.php application / config / routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


$route['myform'] = 'HomeController';
$route['myform/ajax/(:any)'] = 'HomeController/myformAjax/$1';

Step 4: Create Controller 步骤4:创建控制器

Ok, now first we have to create one new controller HomeController with index method. 好的,现在首先我们必须使用索引方法创建一个新的控制器HomeController。 so create HomeController.php file in this path application/controllers/HomeController.php and put bellow code in this file: 因此,请在以下路径application / controllers / HomeController.php中创建HomeController.php文件,并将以下代码放入此文件中:

application/controllers/HomeController.php 应用程序/控制器/ HomeController.php

<?php


class HomeController extends CI_Controller {


   /**
    * Manage __construct
    *
    * @return Response
   */
   public function __construct() { 
      parent::__construct();
      $this->load->database();
   }

   /**
    * Manage index
    *
    * @return Response
   */
   public function index() {
      $states = $this->db->get("demo_state")->result();
      $this->load->view('myform', array('states' => $states )); 
   } 

/** * Manage uploadImage * * @return Response */ / ** *管理uploadImage * * @返回响应* /

   public function myformAjax($id) { 
       $result = $this->db->where("state_id",$id)->get("demo_cities")->result();
       echo json_encode($result);
   }

} }

?> Step 5: Create View Files ?>步骤5:创建视图文件

In this step, we will create myform.php view and here we will create form with two dropdown select box. 在此步骤中,我们将创建myform.php视图,在这里,我们将创建带有两个下拉选择框的表单。 We also write ajax code here: 我们还在这里编写ajax代码:

application/views/myform.php 应用程序/视图/myform.php

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Dependent Dropdown Example with demo</title>
    <script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
    <link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
</head>


<body>
<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Select State and get bellow Related City</div>
      <div class="panel-body">


            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="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>
            </div>


            <div class="form-group">
                <label for="title">Select City:</label>
                <select name="city" class="form-control" style="width:350px">
                </select>
            </div>


      </div>
    </div>
</div>


<script type="text/javascript">


    $(document).ready(function() {
        $('select[name="state"]').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                url:"<?php echo base_url('index.php/Diplome/myformAjax/') ?>"+ stateID,

                    //url: '/myform/ajax/'+stateID,
                    type: "GET",
                    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();
            }
        });
    });
</script>


</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM