Ajax, PHP Problems when receiving data

2

Good people, my problem is this. I have a JS function to do a query in the mysql database via ajax, it returns apparently correctly but when I try to access the value of "undefined" This is an alert (response); being "response" ajax response

HoweveratthetimeItrytoaccessexampleresponse[0].aluno,resultisundefined.

JS

var hora = $this.find('h1').text();
    $.ajax({
        type: "POST",
        dataType: "html",
        url: "alunos.php",
        data: { 'hora': hora},
        success: function(response){
            alert(response);
            // for(var i=0;response.length>i;i++) {
            //    console.log( response[i].nome);
            // }
        }
    });
<?php
header("Content-Type: text/html; charset=UTF-8");

    $mysqli = new mysqli('localhost', 'root', 'vagrant', 'webfit');
    $hora = filter_input(INPUT_POST, 'hora');
    $sql = "SELECT aluno.nome as aluno from aula, aluno_aula,aluno where aluno.id = aluno_aula.aluno_id AND aluno_aula.aula_id=aula.id AND aula.horaini='{$hora}';"; //monto a query
    $query = mysqli_query($mysqli,$sql); //executo a query]
    while($row = mysqli_fetch_assoc($query)){
        $vetor[] = array_map('utf8_encode', $row);
    }
    echo json_encode($vetor);
?>

PHP

    
asked by anonymous 20.10.2017 / 17:27

1 answer

4

If you are able to use the alert, you are receiving a string, convert the json string to an object:

var dados = JSON.parse(response);

You can change the dataType too, like this:

var hora = $this.find('h1').text();
$.ajax({
    type: "POST",
    dataType: 'json',
    url: "alunos.php",
    data: {'hora': hora},
    success: function(response){

    }
});

Example:

$(function(){
  var string = '[{"aluno":"Emilie Dickens"},{"aluno":"Dr. Kenny Reilly Sr."}]';

  var dados = JSON.parse(string);
  alert(dados[0].aluno);
  alert(dados[1].aluno);
});

Link to the working example: link

    
20.10.2017 / 17:29