I would like to know how to get through a ajax request, to bring to my site a list of elements, where these elements are the lines of an sql query. For example, I have a table of employees. In the form, when the user chooses an area, they must fill in a 'select' field for all employees in that area. My code returns only 'undefined'
function buscaNome(area)
{
$("#nomeEsp").empty();
$.ajax({
url: 'php/buscaNomes.php',
type: 'POST',
async: true,
dataType: 'json',
data: {'especialidade':especialidade},
success: function(result) {
if (result != "")
{
var campoSelect = document.getElementById("nomeEsp");
var option = document.createElement("option");
option.text = result[0].nome;
option.value = result[0].nome;
campoSelect.add(option);
}
},
error: function(xhr, status, error) {
alert(status + error + xhr.responseText);
}
});
}
Code that does the query:
class Medico
{
public $nome;
}
try
{
require "conexaoMysql.php";
$listaMedico = "";
$listaMedico = array();
if (isset($_POST["especialidade"]))
$especialidade = $_POST["especialidade"];
$sql = "
SELECT Nome
FROM funcionario
WHERE Especialidade = '$especialidade';
";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($nome);
while($stmt->fetch()){
$medico = new Medico();
$medico->nome = $nome;
$listaMedico[] = $medico;
}
$jsonStr = json_encode($listaMedico);
echo $jsonStr;
}
catch (Exception $e)
{
$msgErro = $e->getMessage();
}
if ($conn != null)
$conn->close();
?>
Note: I put result [0] .name only for test, in theory it should create a for