Pass object by Ajax

Asked

Viewed 730 times

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?

  • 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

1 answer

1


Opa friend all right ?

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 print the code

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

I programmed a similar code for the test and it all worked out: //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 Json 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>

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.