javascript 在codeigniter中带有选择框的Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29593137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:45:42  来源:igfitidea点击:

Ajax with select box in codeigniter

javascriptphpjqueryajaxcodeigniter

提问by Sathya Baman

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. here is my code below.

我试过了,但是我的 ajax 有问题。下面是我的代码。

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_selectselect box.

一旦我选择了一个城市,它必须从数据库中获取该城市的所有区域并将其显示在area_select选择框中。

can any one please help me. Thanks.

谁能帮帮我吗。谢谢。

回答by Shaiful Islam

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_sectioninside ajax success function

还显示area_section里面的ajax成功函数

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'));
                }
              }

回答by Amine Mostefaoui

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

应用程序/配置/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? Step 3: Add Route

另请阅读:如何在 Laravel 5 中使用 jquery ajax 制作简单的依赖下拉菜单?第 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

应用程序/配置/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/';

Step 4: Create Controller

第 4 步:创建控制器

Ok, now first we have to create one new controller HomeController with index method. so create HomeController.php file in this path application/controllers/HomeController.php and put bellow code in this file:

好的,现在首先我们必须使用 index 方法创建一个新的控制器 HomeController。因此在此路径 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 */

/** * 管理上传图片 * * @return 响应 */

   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. We also write ajax code here:

在这一步中,我们将创建 myform.php 视图,在这里我们将创建带有两个下拉选择框的表单。我们这里也写了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>