выбранный вариант с PHP и AJAX - PullRequest
0 голосов
/ 19 марта 2020

Я пытаюсь получить вариант, будет выбран с помощью AJAX, вот мой код:

t_budget_expense:

+--------------------+---------------+------+-----+---------+----------------+
| Field              | Type          | Null | Key | Default | Extra          |
+--------------------+---------------+------+-----+---------+----------------+
| id                 | int(11)       | NO   | PRI | NULL    | auto_increment |
| department         | varchar(128)  | NO   |     | NULL    |                |
| section            | varchar(128)  | NO   |     | NULL    |                |
| budget_id          | varchar(128)  | NO   |     | NULL    |                |
| carmaker           | varchar(128)  | NO   |     | NULL    |                |
| carline            | varchar(128)  | NO   |     | NULL    |                |
| phase              | varchar(128)  | NO   |     | NULL    |                |
| purpose            | varchar(128)  | NO   |     | NULL    |                |

m_purpose:

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| purpose      | varchar(128) | NO   |     | NULL    |                |
| purpose_link | varchar(128) | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

$("a.badge.badge-success.editExpenseModal").on("click", function() {
  const id = $(this).data("id");

  $.ajax({
    url: "http://localhost/bulus-ci/budget/get_expenseByID",
    data: { id: id },
    method: "post",
    dataType: "json",
    success: function(data) {
      $("#id").val(data.id);
      $("#budget_id").val(data.budget_id);
      $('select #purpose option[value="' + data.purpose + '"]').prop(
        "selected",
        true
      );
    }
  });
});
<div class="form-group">
  <select class="custom-select mb-3" id="purpose" name="purpose">
  <?php foreach($purpose as $pur) :?>
    <option value=""><?=$pur['purpose'];?></option>
  <?php endforeach;?>
</div>

Бюджет контроллера. php:

class Budget extends CI_Controller {

//==========================================================
// C O N S T R U C T O R
//==========================================================
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Budget_model');
        is_logged_in();
    }   

//==========================================================
// DEFAULT PAGE
//==========================================================
    public function index()
    {
        $data['user'] = $this->User_model->getUserData();
        $data['role'] = $this->User_model->getUserRole();       
        $data['budget'] = $this->Budget_model->getExpense();
        $data['purpose'] = $this->Budget_model->getPurpose();
        $data['title'] = 'Expense Budget';

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar');
        $this->load->view('templates/topbar');
        $this->load->view('budget/index');
        $this->load->view('templates/footer');
    }

//==========================================================
// EDIT EXPENSE
//==========================================================
    public function get_expenseByID()
    {
        $id = $this->input->post('id');
        echo $this->Budget_model->getExpenseByID($id);
    }   

}   

Модель Budget_model. php:

public function getExpenseByID($id)
{
    $get_id = $id;
    return json_encode($this->db->get_where('t_budget_expense', ['id' => $get_id])->row_array());
}

public function getPurpose()
{
    $this->db->order_by('purpose', 'ASC');
    return $this->db->get('m_purpose')->result_array();
}   

Моя цель - когда пользователи нажимают кнопку редактирования, появляется модальная форма, которая автоматически выбирает поле назначения на основе t_budget_expense, но она не работает с моим текущим кодом

Ответы [ 2 ]

1 голос
/ 19 марта 2020

В выбранном вами виде ввода

 <option value=""><?=$pur['purpose'];?></option>

вам не хватает значения параметра, я думаю, он должен выглядеть как

 <option value="<?= $pur['purpose'] ?>"><?= $pur['purpose'] ?></option>
//Note:value depends on your application requirement "purpose" or  "id"

0 голосов
/ 20 марта 2020
    //controller
    //in edit function  you to send an id on click the edit button and if you are using route then the id will also pass in route. this id is the primary key id of t_budget_expense table.
    public function index($id)
        {
            $data['budget'] = $this->Budget_model->getExpenseById($id);
            $data['purposeArray'] = $this->Budget_model->getPurpose();
            $data['title'] = 'Expense Budget';

            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar');
            $this->load->view('templates/topbar');
            $this->load->view('budget/index');
            $this->load->view('templates/footer');
        }
    //in t_budget_expense model
    function getExpenseById($id){
    return $this->db->where('id',$id)->get('t_budget_expense')->row_array();
    }
    //in m_purpose model
    function getPurpose(){
    return $this->db->get('m_purpose')->result_array();
    }
    //in view
     <select type="text" class="form-control" id="purpose" name="purpose" >
    <option value="" >Select purpose</option>   
            <?php foreach ($purposeArray as $purpose)
                  { ?>
       <option <?php if ($purpose->purpose == $purpose['purpose']) {
                 echo 'selected="selected"';
                 } ?> value="<?php echo $purpose->purpose ?>">
                <?php echo $purpose->purpose ?> </option>
                 <?php } ?>
                 </select>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...