Ajax/JSON returning Undefined

Asked

Viewed 173 times

0

When making an ajax request with JSON return I am receiving Undefined, when showing the data in the console, I receive the code from php page. Can someone help me identify the mistake?

Page: ranking.php

<?php
/**
 * Created by PhpStorm.
 * User: Deivid
 * Date: 14/01/2018
 * Time: 19:44
 * Pagina: Ranking
 */
include 'mysql/conecta_mysql.inc';

$query = mysqli_query($conexao, "SELECT Id, Nome FROM Empresa");
?>

<div class="header-ranking">
    <h2 style="text-align: center; padding-bottom: 4%;"><em class="emIndex">Ranking</em></h2>
</div>

<div class="seletor-ranking" style="padding-bottom: 4%;">
    <form id="form-ranking" method="post" onsubmit="processar(); return false">
        <div class="row">
            <div class="col-md-3 offset-md-1">
                <label for="idSelect" class="control-label col-md-12">Selecione a Empresa:</label>
            </div>
            <div class="col-md-4">
                <div class="col-md-12">
                    <select class="form-control" id="seletorEmpresa" name="seletorEmpresa">
                        <option>Selecione...</option>
                        <?php while ($empresa = mysqli_fetch_array($query)) { ?>
                            <option value="<?php echo $empresa['Id'] ?>"><?php echo $empresa['Nome'] ?></option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="col-md-2">
                <div class="col-md-12">
                    <button id="idConfirmar" name="idConfirmar" class="btn btn-danger">Consultar</button>
                    <!--<button id="idCancelar" name="idCancelar" class="btn btn-danger">Cancelar</button>-->
                </div>
            </div>
        </div>
    </form>
</div>

<div class="modalranking"></div>

<div class="dados-ranking">
    <div class="row">
        <div class="col-md-5 mensal">
            <h4><em class="emIndex">Mensal</em></h4>
            <div class="table-responsive">
                <table class="table table-striped table-bordered table-sm">
                    <thead class="bg-danger">
                    <tr>
                        <th>Posição</th>
                        <th>Motorista</th>
                        <th>KM</th>
                        <th>Pontuação</th>
                    </tr>
                    </thead>
                    <tbody id="rankingMes">
                    </tbody>
                </table>
            </div>
        </div>
        <div class="col-md-5 offset-md-1 anual">
            <h4><em class="emIndex">Anual</em></h4>
            <div class="table-responsive anual">
                <table class="table table-striped table-bordered table-sm">
                    <thead class="bg-danger">
                    <tr>
                        <th>Posição</th>
                        <th>Motorista</th>
                        <th>KM</th>
                        <th>Pontuação</th>
                    </tr>
                    </thead>
                    <tbody id="rankingAno">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>





<script type="text/javascript">
    function processar(){
        $body = $("body");

        $(document).on({
            ajaxStart: function () {
                $body.addClass("loading");
            },
            ajaxStop: function () {
                $body.removeClass("loading");
            }
        });

        getDataMes();
        getDataAno();
        return false;
    }
    function getDataMes() {

        $('#rankingMes').empty();

        var dadosR = {
            "action": "" + $('#seletorEmpresa').val() + ""
        };

        $.ajax({
            type: 'POST',
            url: 'mysql/rankingsMensal.inc',
            datatype: 'json',
            data: dadosR,
            success: function (retorno) {
                if (retorno.error) {
                    console.log(retorno.error);
                }
                else if (typeof retorno.length !== "undefined") {
                    console.log(retorno);
                    var html = "";
                    var len = retorno.length;
                    for (var i = 0; i < len; i++) {
                        var pos = retorno[i].POS;
                        var nome = retorno[i].NOMEMES;
                        var km = retorno[i].KMMES;
                        var pontos = retorno[i].PONTOSMES;

                        html += '<tr>';
                        html += '<td data-label="Posição">' + pos + '</td>';
                        html += '<td data-label="Motorista">' + nome + '</td>';
                        html += '<td data-label="KM">' + km + '</td>';
                        html += '<td data-label="Pontuação">' + pontos + '</td>';
                        html += '</tr>';
                    }
                    $('#rankingMes').html(html);
                }
                else {
                    console.log("Dados inválidos:", retorno);
                }
            }
        });
    }

    function getDataAno() {

        $('#rankingAno').empty();

        var dadosR = {
            "action": "" + $('#seletorEmpresa').val() + ""
        };

        $.ajax({
            type: 'POST',
            url: 'mysql/rankingsAnual.inc',
            datatype: 'json',
            data: dadosR,
            success: function (retornoAno) {
                if (retornoAno.error) {
                    console.log(retornoAno.error);
                }
                else if (typeof retornoAno.length !== "undefined") {
                    var html = "";
                    var len = retornoAno.length;
                    for (var i = 0; i < len; i++) {
                        var pos = retornoAno[i].POS;
                        var nome = retornoAno[i].NOMEMES;
                        var km = retornoAno[i].KMMES;
                        var pontos = retornoAno[i].PONTOSMES;

                        html += '<tr>';
                        html += '<td data-label="Posição">' + pos + '</td>';
                        html += '<td data-label="Motorista">' + nome + '</td>';
                        html += '<td data-label="KM">' + km + '</td>';
                        html += '<td data-label="Pontuação">' + pontos + '</td>';
                        html += '</tr>';
                    }
                    $('#rankingAno').html(html);
                }
                else {
                    console.log("Dados inválidos:", retornoAno);
                }
            }
        });
    }
</script>

Page: rankingsMensal.inc

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

$empresa = $_POST['action'];
$conecta = conecta();
$select  = seleciona($conecta, $empresa);

function conecta(){
    $server   = "zerohoravirtual";
    $usuario  = "zeroh537_master";
    $senha    = "@Logbook";
    $database = "zeroh537_LogBook_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, $idEmpresa) {
    $mesAtual = DATE('m');
    $arrayData = array();

    $mesAtual = str_replace('0','', $mesAtual);

    $kmMes = "";
    $pontosMes = "";
    $idMotorista = "";
    $nomeMotorista = "";

    if($idEmpresa != 0) {
        $queryMes = mysqli_query($conect, "SELECT KMMes, PontosMes, Mes, IdMotorista, IdEmpresa FROM Ranking WHERE Mes = '$mesAtual' AND IdEmpresa = $idEmpresa ORDER BY PontosMes DESC");
        $rowsMes = mysqli_num_rows($queryMes);
        $contagem = 0;

        //variaveis

        while ($rankingMes = mysqli_fetch_array($queryMes)) {
            $kmMes = utf8_encode($rankingMes['KMMes']);
            $pontosMes = utf8_encode($rankingMes['PontosMes']);
            $idMotorista = utf8_encode($rankingMes['IdMotorista']);
            $contagem++;

            $queryMotorista = mysqli_query($conect, "SELECT Nome FROM Motorista WHERE ID = $idMotorista LIMIT 1");
            while ($resultqueryM = mysqli_fetch_array($queryMotorista)) {
                $nomeMotorista = utf8_encode($resultqueryM['Nome']);
            }

            $arrayData[] = array(
                "POS" => $contagem,
                "NOMEMES" => $nomeMotorista,
                "KMMES" => $kmMes,
                "PONTOSMES"  => $pontosMes
            );
        }
    }
    return $arrayData;
}

echo json_encode($select);
?>
  • 2

    Your server is interpreting the files .inc as .php?

  • I had not considered this possibility. I will change the extension and validate.

  • @Valdeirpsr helped me a lot friend. My server was not interpreting the files . inc, I switched to . php and it worked. Thanks friend.

1 answer

0

My server was not interpreting the files .inc, so I switched to .php and it worked.

Browser other questions tagged

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