How to receive a ajax response from a codeigniter controller?

时光总嘲笑我的痴心妄想 提交于 2020-03-18 08:56:47

问题


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.


回答1:


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



回答2:


You can't see "ok" because in ajax parameters you haven't set the dataType. Add one parameter dataType:json/html and then you would be able to receive data from the controller. Something like this:

$.ajax({
   url: "cliente/add",
   type: 'POST',
   data: $("#formCliente").serialize(),
   dataType: 'JSON',
   success: function(msg){
           alert(msg);
           }
});

and replace the controller function into this

public function add()
{
  // validar
  $nome = $this->input->post('inputNome');
  $documento = $this->input->post('inputDocumento');
  $id = $this->Cliente_model->add($nome, $documento);
  echo json_encode($id);
}



回答3:


public function add()
{
    // validar

    $nome = $this->input->post('inputNome');
    $documento = $this->input->post('inputDocumento');
    $insert_id = $this->Cliente_model->add($nome, $documento);
    echo $insert_id; exit;
}



回答4:


To make it more custom you can this is another way to get the response

public function add()
{
    // validar

    $nome = $this->input->post('inputNome');
    $documento = $this->input->post('inputDocumento');
    $res = $this->Cliente_model->add($nome, $documento);

    $this->output
     ->set_status_header(200)
     ->set_content_type('application/json', 'utf-8')
     ->set_output(json_encode($res , JSON_PRETTY_PRINT))
     ->_display();
    exit;
}


来源:https://stackoverflow.com/questions/38688963/how-to-receive-a-ajax-response-from-a-codeigniter-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!