I am creating a form that has a field that the user will enter the company name and Select2 will perform a search in the DB and return the company name to the field, example in the image below:
HTMLscript:
<scriptlanguage="JavaScript" type="text/javascript">
$(document).ready(function() {
$('#nome_pj').select2({
placeholder: "Digite o nome da empresa",
ajax: {
url: 'autosuggest_busca_pessoajuridica.php',
dataType: 'json',
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function(index, item){
results.push({
text: item.nome_pj,
id: item.nome_pj
});
});
return {results: results};
}
}
});
});
Select2 code ( autosuggest_busca_pessoajuridica.php
) to perform BD search:
<?php
include("lib/config.php");
include("lib/util.php");
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Error " . mysqli_error($con));
function destacaTexto($highlite,$string){
return str_ireplace($highlite,"<b>".$highlite."</b>",$string);
}
//Para a busca do auto completar
$input = (isset($_GET['term']))? htmlspecialchars($_GET['term']) :null;
$input = utf8_decode($input);
if ($input!=''){
$data = array();
function toUtf8(&$item, $key) {
$item = iconv("iso-8859-1","utf-8",$item);
}
$query = "SELECT id_feap_pj, tipo_pj, cnpj, nome_pj, endereco_pj, num_end_pj, compl_end_pj, bairro_end_pj, cep_pj, id_mun, uf_pj, telefone_pj, email_pj, nome_representante_pj, cpf_representante_pj, data_cadastro_pj, data_alteracao_pj, id_user
FROM feap_pj
WHERE nome_pj LIKE '%$input%' ";
$result = $con->query($query);
while($row = mysqli_fetch_array($result)) {
array_walk($row, 'toUtf8');
extract($row);
$json = array();
$json['id_feap_pj'] = $id_feap_pj;
$json['tipo_pj'] = $tipo_pj;
$json['cnpj'] = $cnpj;
$json['nome_pj'] = $nome_pj;
$json['endereco_pj'] = $endereco_pj;
$json['num_end_pj'] = $num_end_pj;
$json['compl_end_pj'] = $compl_end_pj;
$json['bairro_end_pj'] = $bairro_end_pj;
$json['cep_pj'] = $cep_pj;
$json['id_mun'] = $id_mun;
$json['uf_pj'] = $uf_pj;
$json['telefone_pj'] = $telefone_pj;
$json['email_pj'] = $email_pj;
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
}
?>
Select2 works normally and can search the DB to return the company name.
I would like as soon as I select the company name, all other information is populated automatically, based on the values contained in the DB, and return in the form fields. How do I do this through Select2?