show user by informed Codeigniter plate

Asked

Viewed 108 times

0

Hello, I would love your help, because I don’t work in the area, but I love to learn, I started to work with codeigniter, I’m making a system for the people of my work, today everything is done in excel. The system is to manage associates, I have a table of plates and name of all employees; My problem is being when I type the plate I can’t pull the name of the person.

In my view I have:

<div class="col-xs-3 form-group">
    <label>Matrícula</label>
    <input style="text-transform:uppercase" class="form-control" type="text" id="matricula" name="matricula" placeholder="Nº matrícula"/>
</div>
<div class="col-xs-6 form-group">
    <label for="nome">Nome</label>
    <input style="text-transform:uppercase"  class="form-control" type="text" id="nome" name="nome" placeholder="Digite a matricula" required/>
</div>

At the end of my view you have the script with an AJAX request

$("input[name='matricula']").blur(function()
{

    event.preventDefault();
    /*
    var matricula = $('#matricula').val();
    */
    var nome = $("input[name='nome']");
    nome.val('Carregando...');

    $.ajax({
        url: baseurl+ 'gesind/pesquisa_mat',
        type: 'POST',
        data: {
            matricula: $('#matricula').val()
        },

        success: function(){
            var nome = data['matricula'];
        },
        error: function(){
            alert("erro");  
        }

    });

});

On my controller I have

public function pesquisa_mat()
    {

        if (!$this->input->is_ajax_request()) 
        { 
            exit('no valid req.'); 
        }
        $usr['matricula'] = $this->input->post('matricula');

        $this->load->model("gesind_model");
        $result = $this->gesind_model->pesquisa_matricula($usr);
        if($result)
        {
            echo $result;
        }
        else
        {
            echo false;
        }

}

and in Model I have the following code

public function pesquisa_matricula($usr) //checks ajax requests
{   
    $this->db->where('matricula',$usr);
    $query=$this->db->get("matriculas");
    if($query->num_rows()>0)
    {
        return $query->result();

    }
    else
    {
        return false;
    }

}

If anyone can help me I’m grateful

1 answer

0


Follow the code below

In Model, we are selecting everything from the table matriculas where the column matricula is equal to a parameter we are passing to the function. The method will return FALSE if you don’t find at least one match in db, otherwise it returns the first line found (I’m assuming there’s only one name per plate)

public function pesquisa_matricula($matricula) {
    $this->db->select('*');
    $this->db->where('matricula',$matricula);
    $query = $this->db->get('matriculas');
    if ($query->num_rows() > 0) {
        return $query->row();
    }else{
        return FALSE;
    }
}

Already in your Controller we are taking the value sent by the request ajax and putting inside the variable $matricula and send this value to our Model search in db. To return the data I used the output class. In it we are saying that we will return a JSON and build it. JSON has 3 fields

  1. data - Contains the user name returned from the Model
  2. error - Informs if there is an error in the query
  3. merro - Error message

This way of returning data facilitates on the front end.

public function pesquisa_mat()  {
    if (!$this->input->is_ajax_request()) {
        exit('no valid req.');
    }
    $matricula = $this->input->post('matricula');

    $this->load->model("gesind_model");
    $result = $this->gesind_model->pesquisa_matricula($matricula);
    if($result) {
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array( 'dados' => $result->nome,
                                        'erro'  => FALSE,
                                        'merro'   => ''
        )));
    }
    else {
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array( 'dados' => '',
                                        'erro'  => TRUE,
                                        'merro'   => 'Usuário não encontrado'
        )));
    }
}

Javascript to make this request follows below. Note we are testing in callback function if my return there is any error and shows the appropriate message to the user. If the query returned no error the script takes the returned value and plays inside the field nome form.

$("input[name='matricula']").blur(function() {
    event.preventDefault();
    var matricula = $('#matricula').val();

    $.ajax({
        url: baseurl+ 'gesind/pesquisa_mat',
        type: 'POST',
        dataType: 'json',
        data: {
            matricula: $('#matricula').val()
        },
        success: function(data){
            if (data.erro) {
                $('#nome').val(data.dados);
                alert(data.merro);
            }else{
                $('#nome').val(data.dados);
            }
        },
        error: function(){
            alert("erro");
        }
    });
});

To check everything I created the table and everything is working as expected. If you continue giving error leave a comment to try to solve.

  • Forgive me Phelipe, but I couldn’t, TRUE when I debug falls on Else { echo "true"; } of controller If I put var_dump($usr); die(); in the Model it shows NULL

  • you have already debugged and tested if the license plate is getting correctly in your controller?

  • $usr=$this->input->post('matricula'); var_dump($usr); die(); the return is NULL, so my problem is before getting to the controller, correct?

  • Exactly. But the modifications you point out are necessary. See the developer tab for what’s coming back. Only go to the Network assignment

  • Okay, I’ll study some more and see where the error is and put again, thank you so much for your support

  • Now appears A PHP Error was encountered Severity: Notice Message: Array to string Conversion Filename: database/Db_query_builder.php Line Number: 683 Backtrace: File: C: xampp htdocs gesind application models Gesind_model.php Line: 80 Function: Where File: C: xampp htdocs gesind application controllers Gesind.php Line: 121 Function: search_matricula

  • and now it’s coming up to the model

  • In the model, change the return to $query->result() and see what happens

  • Good morning Phelipe, continue with the same error. $this->db->Where('matricula',$usr); var_dump($usr); echo "here"; die(); $query=$this->db->get("matricules"); if($query->num_rows()>0) { Return $query->result(); } Else { Return false; } Result: <H4>A PHP Error was encountered</H4> <p>Severity: Notice</p> <p>Message: Array to string Conversion</p> <p>Filename: database/Db_query_builder.php</p> <p>Line Number: 683</p> <p>Backtrace:</p> </div>array(1) { ["matricula"]=> string(6) "127898" } here

  • If possible do the following, update the file of the post pq I will run on my machine and identify the problem.

  • I updated, I’ll do some research too and thanks for your help Phelipe

  • I updated my answer. I created a database and ran the test and it is working perfectly. If you have any problem comments there

  • Caracas brother ran straight, thank you very much

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.