CodeIgniter, Ajax… How to use insert_id()

The name of the picture


CodeIgniter, Ajax… How to use insert_id()



Excuse my English, I hope you can understand my question...



In my program, when you submit a new record to the database (MySQL) using a modal+form, it is drawn in a data table without refreshing or recharging the actual page, it's appended dynamically.



What I need to do is, in every new record, draw/append the data AND 2 buttons (1 for deleting that record and 1 for updating it) with the ID of the new data.



I read I can use insert_id() to get the last inserted id, but I don't know how to use it and how to work with the result in my Ajax call.



Any hint, please? I'm pretty new to programming.



Thanks for your time.



I need the data I introduced in the modal/form (for that I was using .serialize()) AND the ID generated in the DB...
I don't know how to use the model/controller returned ID info.



I have this in my 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));
redirect('/diccionarios/lista_diccionarios');
}
}



Model:


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 (where you see var key = $('input[name="eldi_key"]').val(); and using it, is where I need to use the ID to use the new ID for delete and update clicking the generated buttons):


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





You can add last update data to display records with inserted id.
– C2486
8 hours ago





there are literally so many ways of doing this it is impossible to know which one would work for you. please share your code and read stackoverflow.com/help/mcve
– Alex
8 hours ago





I edited my question, hope it's more clear now... sorry guys
– Nira
7 hours ago





$ret = $this->db->insert_id(); return $ret; try this in the model
– GGw
7 hours ago


$ret = $this->db->insert_id(); return $ret;





I edited again with code and with this -> I need the data I introduced in the modal/form (for that I was using .serialize()) AND the ID generated in the DB...
– Nira
5 hours ago




1 Answer
1



You can use insert_id() only after inserting data to DB. If you need user last id in controller or js try this:


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



Then you can use 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');
}
}



In you js edit success function:


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





I can't make it work... How do I use the id in ajax? using insert_id variable instead of $key?
– Nira
6 hours ago





I edited again with this -> I need the data I introduced in the modal/form (for that I was using .serialize()) AND the ID generated in the DB...
– Nira
5 hours ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS