0
I would like to know how to get through an ajax request, bring to my site a list of elements, where these elements are lines of an sql query. For example, I have an employee chart. In the form, when the user chooses an area, he 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 q makes 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 for test only, in theory I should create a for
Your
$jsonStr
has the right results?– fernandoandrade
Yes, I just can not list all the results, this appearing only the first name, had said it was appearing Undefined, but no. Only the first line of the query is appearing
– Bruno Inácio