Problems with using Ajax request

0
When I try to make a request to return an sql query to the form fields it returns only the first row of the table, how can I change my code to search for all rows:

code that makes select:

<?php
class Medico 
{
 public $nome;
}

try 
{
require "conexaoMysql.php";

$medico = "";
$especialidade = "";
if (isset($_POST["especialidade"]))
  $especialidade = $_POST["especialidade"];

$SQL = "
 SELECT Nome
 FROM funcionario
 WHERE Especialidade = '$especialidade';
";

if (! $result = $conn->query($SQL))
 throw new Exception('Ocorreu uma falha ao buscar os nomes: ' . $conn-
>error);

if ($result->num_rows > 0)
{
   $row = $result->fetch_assoc();

$medico = new Medico();

$medico->nome = $row["Nome"];

} 

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

}

Requesting function code

function buscaNome(especialidade)
{
 $("#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.nome;
        option.value = result.nome;
        campoSelect.add(option);

    }
  },

  error: function(xhr, status, error) {
    alert(status + error + xhr.responseText);
  }

});  

}

Note: Results are placed in a select html field

    
asked by anonymous 10.11.2017 / 21:59

1 answer

0

First the fetch_assoc function returns only one row of the resultset at a time. So that all rows returned from the bank are accessed it is necessary to use a while loop to iterate over all rows returned by the bank. This can be done like this:

//array de medicos
$medicos = [];

if ($result->num_rows > 0)
{
    while($row = $result->fetch_assoc()){
        $medico = new Medico();
        $medico->nome = $row["Nome"];
        $medicos[] = $medico;
    }
} 

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

As can be seen in the code, it is necessary to return an array of doctors (instead of just an object of the medical class). Because every iteration in the while loop creates a new medical object.

The change in the form of the return causes a change in the javascript. Now it is necessary to add a repeat loop to access the indexes of the result vector. Setting stays:

if (result != "")
{                  
    for(var i = 0; i < result.length; i++){
        var campoSelect = document.getElementById("nomeEsp");
        var option = document.createElement("option");
        option.text = result[i].nome;
        option.value = result[i].nome;
        campoSelect.add(option);
    }

}

Serialize private variables with json_encode

If your Medico class has private attributes, they will not be automatically serialized with json_encode . For this to happen you should implement the JsonSerializable interface, more about it in php.net . Doing this looks something like this:

    <?php
class Medico implements JsonSerializable{
    private $nome;
    public function setNome($nome){
        $this->nome = $nome;
    }

    public function jsonSerialize(){
        return ['nome' => $this->nome]; 
    }
}

$medico1=new Medico();
$medico1->setNome('nome1');
$medico2=new Medico();
$medico2->setNome('nome2');

echo json_encode([$medico1, $medico2]);

The most important thing is not how the name parameter is sent to the class, but the existence of the jsonSerialize() function. By doing this something is printed on the console something like this:

[{"nome":"nome1"},{"nome":"nome2"}]

This should solve the problem of undefined presented with previous versions of the code.

    
11.11.2017 / 02:43