Ajax не может загрузить каскадный выбор - PullRequest
0 голосов
/ 04 мая 2019

Я использую codeIgniter и ajax для реализации каскадного выбора, к сожалению, не работает и выдает эту ошибку на chrome w3dev.js:3355 POST http://schools.phlitz.org/academic/student_add/request_districts 500 (Internal Server Error), а на Firefox Empty string passed to getElementById().

Моя функция контроллера

function student_add($param1 = '', $param2 = '', $param3 = '') {
        if ($this->session->userdata('academic_login') != 1)
         redirect('login', 'refresh');
     if ($param1 == 'create') {

         $data['admission_form_no'] = $this->input->post('admission_form_no');
         $data['registration_no'] = $this->input->post('registration_no');
         $data['student_unique_ID'] = $this->input->post('student_unique_ID');

         $data['name'] = $this->input->post('name');
         $data['birthday'] = $this->input->post('birthday');
         $data['sex'] = $this->input->post('sex');

         $data['email'] = $this->input->post('email');
         $data['religion'] = $this->input->post('religion');
         $data['nationality'] = $this->input->post('nationality');
         $data['password'] = md5($this->input->post('password'));

         $data['guardian_name'] = $this->input->post('guardian_name');
         $data['guardian_profession'] = $this->input->post('guardian_profession');
         $data['relation_to_student'] = $this->input->post('Relation_to_student');
         $data['guardian_address'] = $this->input->post('guardian_address');
         $data['guardian_nid'] = $this->input->post('guardian_nid');
         $data['gardian_mobile'] = $this->input->post('gardian_mobile');


         $data['prev_institution_name'] = $this->input->post('prev_institution_name');
         $data['prev_class_id'] = $this->input->post('prev_class_id');
         $data['prev_passing_yrs'] = $this->input->post('prev_passing_yrs');
         $data['prev_gpa'] = $this->input->post('prev_gpa');
         $data['prev_institution_address'] = $this->input->post('prev_institution_address');


         $data['clearance_no'] = $this->input->post('clearance_no');


         $mainsubject =$this->input->post('mainsubject');
         if($mainsubject){
         $strsubject="";
         foreach ($mainsubject as $hobys=>$value) {
         $strsubject.=$value."SC";
             }
         }
         if($mainsubject){
         $data['subject_id'] = $strsubject;
         }

         $forthsubject =$this->input->post('forthsubject');
         if($forthsubject){
         foreach ($forthsubject as $hobys=>$value) {
         $strforthsubject=$value;
             }
         }
         if($forthsubject){
         $data['fourth_id'] = $strforthsubject;
         }

         $data['class_id'] = $this->input->post('class_id');

         $data['roll'] = $this->input->post('roll');
         $data['section'] = $this->input->post('section');
         $data['group'] = $this->input->post('group');

         $data['passing_year'] = $this->input->post('passing_year');
         $data['other_student_name'] = $this->input->post('other_student_name');
         $data['others_class_id'] = $this->input->post('others_class_id');
         $data['group_others'] = $this->input->post('group_others');
         $data['others_section'] = $this->input->post('others_section');
         $data['others_roll'] = $this->input->post('others_roll');

         $this->db->insert('student', $data);
         $student_id = $this->db->insert_id();
         move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/student_image/' . $student_id . '.jpg');

         redirect(base_url() . 'index.php?academic/student_add/', 'refresh');
     }

     if ($param1 == 'request_districts') {
         $region_id = $this->input->post('region');
         if($region_id != ''){
             $this->crud_model->get_district($region_id);
         }
     }

     $page_data['page_name'] = 'student_add';
     $page_data['page_title'] = get_phrase('manage_student');
     $this->load->view('index', $page_data);
 }

Функция модели

function get_district($region_id){
        $this->db->where('region_id', $region_id);
        $this->db->order_by('name', 'ASC');
        $query = $this->db->get('districts');
        //return $query->result();
        $output = '<option value="">Select district</option>';
        foreach($query->result() as $row)
        {
            $output .= '<option value="'.$row->id.'">'.$row->name.'</option>';
        }
      return $output;
    }

Просмотр файла с функцией JavaScript

<p>
<select name="region" class="uniform" style="width:100%;" id = "region">
  <option value="">Select Region of residence</option>
<?php
   echo make_select('regions','id','name');
?>
 </select>
</p>
<p>
   <select name="district" class="uniform" style="width:100%;" id = "district">
  <option value="">Select District of residence</option>    
</select>
</p>

Регионы заполнены make_select() правильно

$(document).ready(function(){
     $('#region').change(function(){
      var region_id = document.getElementById("region").value;
      //alert(region_id);
      if(region_id != '')
      {
       $.ajax({
        url:"<?php echo base_url(); ?>academic/student_add/request_districts",
        method:"POST",
        dataType: "html",
        data:{region_id:region_id},
        success:function(data)
        {
         $('#district').html(data);
        }
       });
      }
      else
      {
       $('#district').html('<option value="">Select district</option>');
      }
     });
    });

Любой, кто может мне помочь, пожалуйста,Я сложил здесь два дня!

Ответы [ 2 ]

0 голосов
/ 05 мая 2019

На тот случай, если у других возникла такая проблема, я понял, что я использую защиту CSRF в своем приложении, поэтому я просто добавил токен CSRF в свой пост javascript и решил все, теперь мой JS выглядит так

$(document).ready(function() {
        $('#region').change(function() {
            var region_id = document.getElementById("region").value;
            var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>';
            var csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';

            if (region_id != '') {
                $.ajax({
                    url: "http://schools.phlitz.org/index.php?academic/getDistrict",
                    method: "POST",
                    dataType: "html",
                    data: {
                        [csrfName]:csrfHash,
                        'region_id': region_id
                    },
                    success: function(data) {
                        //alert(data);
                        $('#district').html(data);
                    }
                });
            } else {
                $('#district').html('<option value="">Select district</option>');
            }
        });
    });

Спасибо.

0 голосов
/ 04 мая 2019

Контроллер:

function getDistrict(){
   $region_id = $this->input->post('region');
   $optionHtml =  $this->crud_model->get_district($region_id);
   echo $optionHtml;
   //here you can load html file too
   //$data = array();
   //$data['optionHtml'] = $optionHtml;
   //$this->load->view('district',$data);
}
district.php
<?php echo $optionHtml; ?>

Модель:

function get_district($region_id){
        $this->db->where('region_id', $region_id);
        $this->db->order_by('name', 'ASC');
        $query = $this->db->get('districts');

        $output = '<option value="">Select district</option>';
        foreach($query->result() as $row)
        {
            $output .= '<option value="'.$row->id.'">'.$row->name.'</option>';
        }
      return $output;
    }

Ajax:

$(document).ready(function() {
    $('#region').change(function() {
        var region_id = document.getElementById("region").value;
        //alert(region_id);
        if (region_id != '') {
            $.ajax({
                url: "<?php echo base_url(); ?>academic/student_add/getDistrict",
                method: "POST",
                dataType: "html",
                data: {
                    region_id: region_id
                },
                success: function(data) {
                    $('#district').html(data);
                }
            });
        } else {
            $('#district').html('<option value="">Select district</option>');
        }
    });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...