Greetings to all, I am using a select2 so you can bring me data from the mysql database by selecting an option from select2 which is linked to the database through ajax
javascript code:
$("#buscar_clientes").select2({
placeholder: ‘Escriba la cédula o el nombre del cliente’,
minimumInputLength: 3,
allowClear: true,
ajax: {
url: ‘…/modelos/buscar_cliente.php’,
dataType: ‘json’,
type: “GET”,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.nombre,
id: item.Id_cliente
}
})
};
success: function (response) {
console.log(response);
$(’#cliente’).empty();
$(’#cliente’).val(response);
}
}
},
and the ajax code:
define (‘DB_USER’, “root”);
define (‘DB_PASSWORD’, “140469”);
define (‘DB_DATABASE’, “veterinaria_lte”);
define (‘DB_HOST’, “localhost”);
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
mysqli_set_charset( $mysqli, ‘utf8’);
$sql = “SELECT cedula, Id_cliente, nombre, nombre_mascota, telefono, celular FROM clientes
WHERE cedula = '”.$_GET[‘q’]."’ OR nombre LIKE ‘%".$_GET[‘q’]."%’
LIMIT 10";
$result = $mysqli->query($sql);
$return_arr = array();
while($row = $result->fetch_assoc()){
$json[] = [‘id’=>$row[‘Id_cliente’], ‘text’=>$row[‘nombre’].’ | ‘.$row[‘cedula’].’ | '.$row[‘nombre_mascota’]];
}
echo json_encode($json);