CodeIgniter,Ajax...如何使用insert_id()

CodeIgniter, Ajax... How to use insert_id()

对不起我的英文,希望你能理解我的问题...

在我的程序中,当你使用模态+表单向数据库(MySQL)提交一条新记录时,它被绘制在一个数据table中,而没有刷新或充电实际页面,它是动态附加的。

我需要做的是,在每条新记录中,draw/append 数据和 2 个按钮(1 个用于删除该记录,1 个用于更新它)以及新数据的 ID。

我读到我可以使用 insert_id() 来获取最后插入的 ID,但我不知道如何使用它以及如何在我的 Ajax 调用中处理结果。

有什么提示吗?我对编程还很陌生。

感谢您的宝贵时间。

编辑

我需要我在 modal/form 中引入的数据(为此我使用了 .serialize())以及在数据库中生成的 ID... 我不知道如何使用 model/controller 返回的 ID 信息。

我的控制器里有这个:

    public function nuevo_elemento_diccionario()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    // Validation rules that I deleted for this post
    if ($this->form_validation->run() === FALSE)
    {              
        $this->load->view("header");
        $this->load->view("section-aside");
        $this->load->view("vista_nuevo_elemento_diccionario", $datos);
        $this->load->view("footer");
    }
    else
    {
        $last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
        echo json_encode(array('last_id' => $last_id));
        redirect('/diccionarios/lista_diccionarios');
    }
}

型号:

public function nuevo_elemento_diccionario()
 {
     $datos = array(
        'ELDI_Key' => $this->input->post('eldi_key'),
        'ELDI_Display' => $this->input->post('eldi_display'),
        'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
    );
    $this->db->insert('elementos_diccionario', $datos);
   /* $ultima_id = $this->db->insert_id();*/
    $last_id = $this->db->insert_id();
    return  $last_id;
  }

Javascript/Ajax(你看到 var key = $('input[name="eldi_key"]').val(); 并使用它,我需要使用 ID 来使用新 ID 进行删除和单击生成的按钮更新):

function nuevo_elemento() 
{
    var id =$('input[name="eldi_id"]').val();
    var display = $('input[name="eldi_display"]').val();
    var key = $('input[name="eldi_key"]').val();
    key = key.split(" ").join("_").toLowerCase();

    swal({
        title: 'Añadir elemento',
        text: "¿Quieres añadir este elemento?",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Sí',
        cancelButtonText: 'No'
        }).then((result) => {
        if (result.value) {
            $.ajax({
                type: "POST",
                url: $("#base_url").attr("valor") + 
 "diccionarios/nuevo_elemento_diccionario",
                data: $("#formNuevoElementoDiccionario").serialize(),
                success: function(data) {
                    console.log(data);
                    $('#Modal_Add').modal('hide');

                    $("#formNuevoElementoDiccionario").trigger("reset");

                    var html = 
                    '<tr>'+
                        '<td>' + key + '</td>' +
                        '<td>'+ display +'</td>'+
                        '<td>'+
                            '<span class="btn btn-default editar_elemento" 
 id=' + key + ' value="' + key + '">' +
                                '<a href="'+$("#base_url").attr("valor") + 
 "diccionarios/elemento_diccionario/"+key+'" title="Editar">' +
                                    '<i class="material-icons">edit</i>' +
                                '</a>' +
                            '</span>' +
                        '</td>' + 
                        '<td>' +
                            '<span class="btn btn-default borrar_elemento" 
 id="'+ key +'" value="'+ key +'">'+
                                    '<i class="material- 
 icons">delete_outline</i>'+   
                            '</span>'+
                        '</td>'+
                    '</tr>'

                    $('#tabla-diccionarios').append(html);
                    swal("Añadido", "Elemento añadido correctamente", 
"success");

                    $(".borrar_elemento").off();                        
                    evento_borrar_elemento();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("Error: " + textStatus);
                    }
            });
        }
        })
}

只有在向数据库中插入数据后才能使用insert_id()。如果您需要控制器或 js 中的用户最后一个 ID,请尝试以下操作:

public function nuevo_elemento_diccionario()
{
    $datos = array(
        'ELDI_Key' => $this->input->post('eldi_key'),
        'ELDI_Display' => $this->input->post('eldi_display'),
        'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
    );
    $this->db->insert('elementos_diccionario', $datos);
    $ultima_id = $this->db->insert_id();
    return $ultima_id;
}

然后你可以使用json_encode() for return data to js in Controller:

public function nuevo_elemento_diccionario()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    // Validation rules that I deleted for this post
    if ($this->form_validation->run() === FALSE)
    {              
        $this->load->view("header");
        $this->load->view("section-aside");
        $this->load->view("vista_nuevo_elemento_diccionario", $datos);
        $this->load->view("footer");
    }
    else
    {
        $last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
        echo json_encode(array('last_id' => $last_id));
        // i`m not sure that you need to use redirect
        redirect('/diccionarios/lista_diccionarios');
    }
}

在你的js中编辑成功函数:

 success: function(data) {
     var result = JSON.parse(data);
     var insert_id = result.insert_id;