Ramon Carvalho
Ramon Carvalho

Reputation: 112

How to receive a ajax response from a codeigniter controller?

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.

Upvotes: 2

Views: 11010

Answers (4)

Nikhil
Nikhil

Reputation: 312

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

Upvotes: 5

EdyGorbacev
EdyGorbacev

Reputation: 11

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

Upvotes: 1

Deepak Singh
Deepak Singh

Reputation: 650

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

Upvotes: 2

user5200704
user5200704

Reputation: 1709

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

Upvotes: 1

Related Questions