Pass object by Ajax

0

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

    
asked by anonymous 15.11.2017 / 02:29

1 answer

1

Oops, my friend, how are you?

Do the following:

// In the medical class creates a method that transforms the Object into Json

class Medico 
{
    public $nome;

    public function JsonRetorno()
    {
        return json_encode(get_object_vars($this));
    }
}

// Instead of an array of objects create an array of json

while($stmt->fetch()){
    $medico = new Medico();

    $medico->nome = $nome;

    $listaMedico[] = $medico->JsonRetorno();
 }

// To start the code

 $jsonStr = json_encode($listaMedico);
 echo $jsonStr;

I programmed a similar test code and it worked: // Medical class

Class Medico
{
    private  $nome;
    private  $login;
    private  $senha;

    public function setNome($nome)
    {
        $this->nome = $nome;
    }

    public function setLogin($login)
    {
        $this->login  = $login;
    }

    public function setSenha($senha)
    {
        $this->senha = $senha;
    }

    public function JsonRetorno()
    {
        return json_encode(get_object_vars($this));
    }
}

// Main class

include("Medico.php");

Class Main
{
    function __construct()
    {

        $medicos = [];
        $medico = new Medico();
        $medico->setNome("Vinicius");
        $medico->setLogin("AnjoNegro");
        $medico->setSenha("StackOverFlow");

        $medicos[] = $medico->JsonRetorno(); //Adiciona médico para array Json 

        $medico2 = new Medico();
        $medico2->setNome("Vinicius2");
        $medico2->setLogin("AnjoNegro2");
        $medico2->setSenha("StackOverFlow2");
        $medicos[] = $medico2->JsonRetorno();

        echo json_encode($medicos);

    }
}

$objMain = new Main();

// An example of Json's capture in html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="http://zeptojs.com/zepto.min.js"type="text/javascript">
    </script>
    <script>
        $.getJSON("main.php", function(data) {
            $("html").html(data);
        });
    </script>
</head>

<body>

</body>

</html>

    
15.11.2017 / 19:19