I have a controller that send the data to the model and the model insert this data in the mysql.
I want to know the last ID of the row inserted, but I want this ID in my ajax function to use to uptade the table with the information.
Here what I have:
The model:
public function add($nome, $documento)
{
$dados = array (
'nome' => $nome,
'documento' => $documento
);
$this->db->insert('clientes', $dados);
return $this->db->insert_id();
}
The Controller:
public function add()
{
// validar
$nome = $this->input->post('inputNome');
$documento = $this->input->post('inputDocumento');
$this->Cliente_model->add($nome, $documento);
return "ok";
}
The ajax function:
$(document).ready(function(){
$("#salvarCliente").click(function(){
$.ajax({
url: "cliente/add",
type: 'POST',
data: $("#formCliente").serialize(),
success: function(msg){
alert(msg);
$("#clienteMensagem").html('Cliente cadastrado com sucesso!');
$("#table-clientes tr:last").after('<tr><td>'+msg+'</td><td>' + $('#clienteNome').val() + '</td><td>' + $('#clienteDocumento').val() + '</td><td></td></tr>');
$("#clienteNome").val('');
$("#clienteDocumento").val('');
}
});
return false;
});
});
The code add my data to mysql, but I can't see the "ok" from the controller on my console.log or in my alert in the browser before I send the data.
I only want to return the result of "$this->db->insert_id()" from my model to my controller and from my controller to my ajax function.
Change following:
The controller :
public function add()
{
// validar
$nome = $this->input->post('inputNome');
$documento = $this->input->post('inputDocumento');
$res = $this->Cliente_model->add($nome, $documento);
echo json_encode($res);
}
The ajax function:
$(document).ready(function(){
$("#salvarCliente").click(function(){
$.ajax({
url: "cliente/add",//Enter full URL
type: 'POST',
dataType:'JSON',
data: $("#formCliente").serialize(),
success: function(msg){
alert(msg);
$("#clienteMensagem").html('Cliente cadastrado com sucesso!');
$("#table-clientes tr:last").after('<tr><td>'+msg+'</td><td>' + $('#clienteNome').val() + '</td><td>' + $('#clienteDocumento').val() + '</td><td></td></tr>');
$("#clienteNome").val('');
$("#clienteDocumento").val('');
}
});
return false;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With