Ajax, PHP Problems when receiving data

Asked

Viewed 62 times

2

Okay, guys, here’s my problem. I have a JS function to make a query in mysql database via ajax, it returns apparently correctly but when I try to access the value of "Undefined" This is an Alert(Sponse); being "Answer" ajax response

Isto é um alert(response)

however at the time I try to access example Answer[0]. student, result is Undefined.

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

1 answer

4


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

var dados = JSON.parse(response);

You can change dataType too, this way:

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 with example working: https://jsfiddle.net/ws5guo6m/1/

  • If I make any of these changes I get: [Object Object],[Object Object] in the place where I received what is represented in Alert. That’s what’s bothering me these changes should work.

  • But that’s right, now you have to manipulate the object.

  • I will make an example and post here in the reply, just a minute.

  • I updated the example

  • 1

    Dude, thank you so much for this idea of JSON.parse(string), solved as follows: var data = JSON.parse(Answer);

Browser other questions tagged

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