How to fill inputs with data retrieved from mysql from a select2 and ajax


#1

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


#2

Your response data must be returned in a JSON object with a “data” property whose value is the array of items you want to fill the select2. Your PHP code is returning the array, but it’s not wrapped in the JSON object.

Also, if you will rename the “nombre” field to “text” in your returned array items then you won’t need to map them on the JavaScript side.


#3

thanks for your reply