如何接收来自Codeigniter控制器的Ajax响应? [英] How to receive a ajax response from a codeigniter controller?
问题描述
我有一个将数据发送到模型的控制器,模型将这些数据插入mysql中.
I have a controller that send the data to the model and the model insert this data in the mysql.
我想知道插入的行的最后一个ID,但是我想在我的ajax函数中使用该ID来更新表中的信息.
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.
这是我拥有的:
模型:
public function add($nome, $documento)
{
$dados = array (
'nome' => $nome,
'documento' => $documento
);
$this->db->insert('clientes', $dados);
return $this->db->insert_id();
}
控制器:
public function add()
{
// validar
$nome = $this->input->post('inputNome');
$documento = $this->input->post('inputDocumento');
$this->Cliente_model->add($nome, $documento);
return "ok";
}
ajax函数:
$(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;
});
});
代码将我的数据添加到mysql中,但是在发送数据之前,我无法从console.log或浏览器的警报中看到来自控制器的确定".
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.
我只想将"$ this-> db-> insert_id()"的结果从我的模型返回到我的控制器,再从我的控制器返回到我的ajax函数.
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.
推荐答案
更改以下内容:
控制器:
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);
}
ajax函数:
$(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;
});
});
这篇关于如何接收来自Codeigniter控制器的Ajax响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!