Ajax is returning Undefined

Asked

Viewed 656 times

1

Guys, I’m just trying to list the names I have in the bank, but the message undefined, can anyone help? Below is jquery + the query to the bank.

jQuery:

<body>
    <script>
        $(document).ready(function() {
            $('#relatorio').click(function(event) {
                $.ajax({
                    type: 'post',
                    datatype: 'json',
                    url: 'ajax.php',
                    success: function(retorno){
                        for (var i = 0; i < retorno.length; i++) {
                            console.log(retorno[i].nome);
                        };

                    }
                })
            });         
        });
    </script>
    <input type="submit" name="Relatorio" value="Relatorio" id="relatorio">     
</body>

Consulted at the bank:

<?php   

$conect = conecta();    
$select  = seleciona($conect);
echo json_encode($select);

function conecta() {
    $server   = "localhost";
    $usuario  = "root";
    $senha    = "";
    $database = "teste";
    $conexao  = mysqli_connect($server, $usuario, $senha) or die(); 
    mysqli_select_db($conexao, $database);
    return $conexao;
}
function seleciona($conect) {
    $guarda = array();
    $query    = "SELECT * FROM teste";
    $executa  = mysqli_query($conect, $query);  
    $i = 0;     
    while ($resultado = mysqli_fetch_array($executa)) {
        $guarda[] = array('nome'=> (utf8_encode($resultado['nome'])));
    }
    return $guarda;
}
?>
  • Welcome to Stack Overflow in English, please avoid cashier and make more detailed headlines. I hope you get the result.

  • Where does it lead undefined?

  • The return, when I print on the console

  • @Jeffersonsantos Response code has been modified.

  • Perfect, how do I print on the body of the page? Thank you very much for the help, can you explain to me what parts of codes inserted?

  • Good evening, I wonder if any of the answers helped you, if not please comment on what you think is missing.

Show 1 more comment

1 answer

3

Try this, this will generate an error json, like this {error: "Erro de conexão"}:

$conexao  = mysqli_connect($server, $usuario, $senha) or die(json_encode(array(
    'error' => mysqli_connect_error()
)));

and this will generate the Content-Type for the answer of jQuery:

header('Content-Type: application/json');

Code php should look like this:

<?php
header('Content-Type: application/json');

$conect = conecta();    
$select  = seleciona($conect);
echo json_encode($select);

function conecta() {
    $server   = "localhost";
    $usuario  = "root";
    $senha    = "";
    $database = "teste";
    $conexao  = mysqli_connect($server, $usuario, $senha) or die(json_encode(array(
        'error' => mysqli_error()
    ))); 
    mysqli_select_db($conexao, $database);
    return $conexao;
}

function seleciona($conect) {
    $guarda = array();
    $query    = "SELECT * FROM teste";
    $executa  = mysqli_query($conect, $query);  
    $i = 0;     
    while ($resultado = mysqli_fetch_array($executa)) {
        $guarda[] = array('nome'=> (utf8_encode($resultado['nome'])));
    }
    return $guarda;
}
?>

And jQuery should stay like this:

success: function(retorno){
    //Está linha detecta um erro de conexão
    if (retorno.error) {
        console.log(retorno.error);

    //Está linha detecta se a resposta é um array
    } else if (typeof retorno.length !== "undefined") {
        for (var i = 0; i < retorno.length; i++) {
            console.log(retorno[i].nome);
        };

    //Está linha detecta se houve falha na resposta e envia o para o log
    } else {
        console.log("Dados inválidos:", retorno);
    }
}

Complete code:

<body>
    <script>
        $(document).ready(function() {
            $('#relatorio').click(function(event) {
                $.ajax({
                    type: 'post',
                    datatype: 'json',
                    url: 'ajax.php',
                    success: function(retorno){
                        if (retorno.error) {
                            console.log(retorno.error);
                        } else if (typeof retorno.length !== "undefined") {
                            for (var i = 0; i < retorno.length; i++) {
                                console.log(retorno[i].nome);
                            };
                        } else {
                            console.log("Dados inválidos:", retorno);
                        }
                    }
                })
            });         
        });
    </script>
    <input type="submit" name="Relatorio" value="Relatorio" id="relatorio">     
</body>

To add to the HTML body, you must use .html, .appendTo and others you can read on jQuery documentation:

<body>
    <script>
        $(document).ready(function() {
            $('#relatorio').click(function(event) {
                $("#resposta").html("Carregando...");
                $.ajax({
                    type: 'post',
                    datatype: 'json',
                    url: 'ajax.php',
                    success: function(retorno){
                        if (retorno.error) {
                            $("#resposta").html(retorno.error);
                        } else if (typeof retorno.length !== "undefined") {
                            $("#resposta").html("");
                            for (var i = 0; i < retorno.length; i++) {
                                //Gera novos paragrafos:
                                $("<p></p>").html(retorno[i].nome).appendTo("#resposta");
                            };
                        } else {
                            $("#resposta").html("Dados inválidos:" + retorno);
                        }
                    }
                })
            });         
        });
    </script>
    <input type="submit" name="Relatorio" value="Relatorio" id="relatorio">
    <div id="resposta"></div>
  </body>
  • Perfect, how do I print on the body of the page? Thank you very much for the help, can you explain to me what parts of codes inserted?

  • That’s right, I want to add to an html.

  • Thank you so much for the strength William, so console.log(return[i].name); instead I want to play on the screen this return.

  • I got William, thank you very much for everything, abs

  • @Jeffersonsantos If the answer solved the problem, please mark it as correct, if you do not know how to do this, see the tour: http://answall.com/tour

Browser other questions tagged

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