Get INT as INT and not as string - Codeigniter - Ajax

Asked

Viewed 98 times

1

I have the following tabela, controller and model, I want to get what it is int as int, and not string.

Note that when the item is recovered, the field int is in quotes. How do I recover the data correctly ?

Table

DROP TABLE IF EXISTS `tbl_banco`;
CREATE TABLE IF NOT EXISTS `tbl_banco` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `codigo` VARCHAR(5) NOT NULL,
  `nome` VARCHAR(255) NOT NULL,
  `assessoria_id` INT(11) NOT NULL,
  `dt_cadastro` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `dt_atualizacao` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `situacao` TINYINT(1) NULL DEFAULT NULL,
   PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARSET = utf8;

Controller

//Função Obter Banco por ID
public function obter($id)
{
    if ($id == 0)
    {
        $id = $id;
        $dados = $this->banco->json_array($id);
        echo json_encode($dados);
    }
    else
    {
        $dados = $this->banco->obter($id);
        echo json_encode($dados);
    }
}

Model

/*** Obter por ID ***/
public function obter($id)
{
    $this->db->from($this->tbl_banco);
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->row_array();
}

Ajax

function obter(id, acao) {
var ret;
$.ajax({
    type: 'GET',
    async: false,
    contentType: 'application/json',
    url : "banco/obter/" + id + "/" + acao,
    success: (function (obj) {          
        _obj = JSON.parse(obj);
        _obj_banco = _obj;
        objeto_form();
        ret = true;
    }),
    error: (function (erro) {
        trata_erro_ajax(erro);
        ret = false;
    })
});
return ret;
}

inserir a descrição da imagem aqui

1 answer

1


Can you solve with JSON_NUMERIC_CHECK, an option of json_encode which was added in PHP 5.3.3

Problem and that this will transform into int all the numbers that it achieves, for example your codigo will return as 1 instead of 001

Just add the option at Encode time echo json_encode($dados, JSON_NUMERIC_CHECK);

More Infos Voce can be found in json_encode Docs()

  • But then, as you said, this constant JSON_NUMERIC_CHECK, will force the return of all that is number, even if the field type is varchar or char. If to retrieve one CPF, whose first number is 0, he will disregard this 0. Has some other form ?

  • This is where you find the controller function, treat the values and send the result to the user. So, ideally go through the array and treat the values.

  • Yes, the database is mysql

Browser other questions tagged

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