Get a JSON PHP Via Jquery

0

I have 3 pages, 1-Index, where I pass some settings; 2- game_data.php, where a query is made and returns a json with the data; 3- juego.php, The page where the json data is displayed is displayed.

My difficulty now is, get this data from Json generated by PHP, I think they are getting lost the moment I give the Header to the other pag, how do I treat it better? Here is the "Internal Server Error" returned, is there any way I can verify this error?

Index

<div class="container-fluid">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <h3 class="text-center">Antes de iniciar vamos definir algumas configurações</h3><br /><br />
    </div>
    <div class="col-md-6 col-md-offset-3" id="config">
      <div class="alert alert-success" role="alert" id="success">
           <!--Div acionada via JS-->
      </div>
        <form id="jogo" action="dados_jogo.php" Method="POST">
                    <div class="input-group">
                     <span class="input-group-addon"><img src="img/nome.ico"></span>
                       <input type="text" id="equipe" name="equipe1" class="form-control" placeholder="Nome da primeira Equipe" aria-describedby="basic-addon1">
                      </div>
                      <br>
                      <div class="alert alert-danger" id="valida_equipe" role="alert">
                        <span class="glyphicon glyphicon-info-sign"></span> Preencha o nome da primeira equipe
                      </div>
                    <div class="input-group">
                     <span class="input-group-addon"><img src="img/nome.ico"></span>
                      <input type="text" id="equipe2" name="equipe2" class="form-control" placeholder="Nome da Segunda Equipe" aria-describedby="basic-addon1">
                       </div>
                       <br>
                       <div class="alert alert-danger" id="valida_equipe2" role="alert">
                         <span class="glyphicon glyphicon-info-sign"></span> Preencha o nome da segunda Equipe
                       </div>


                  <div class="form-group">
                    <label for="select">Selecione a Dificuldade</label>
                      <select class="form-control" id="dificuldade" name="dificuldade">
                        <option value="1">Fácil</option>
                        <option value="2">Médio</option>
                        <option value="3">Difícil</option>
                      </select>
                    </div>
                    <div class="form-group">
                      <label for="select">Selecione o número de perguntas da rodada:</label>
                        <select class="form-control" id="rodada" name="rodada">
                          <option value="1">10</option>
                          <option value="2">15</option>
                          <option value="3">20</option>
                        </select>
                      </div>
                  <center>
                    <input type="submit" class="btn btn-primary btn-lg" id="iniciar" value="Iniciar o jogo">
                     <button type="button" class="btn btn-primary btn-lg" id="refresh">Nova Tentativa</button>                  </center><br><br>
                 </form>
            <br>
      </div>

    </div>

  </div>

Config.PHP

<?php
header('Content-Type: application/json, charset=UTF-8');
$equipe1 = $_POST['equipe1'];//Pega o Nome da equipe
$equipe2 = $_POST ['equipe2'];//Pega o Nome da equipe
$dificuldade = $_POST ['dificuldade'];//Define a dificuldade das perguntas que seram selecionadas
$rodada = $_POST ['rodada'];//Número de perguntas que serão retornadas


switch ($dificuldade) {
  case '1':
    $dificuldade = "Facil";
    break;
  case '2':
    $dificuldade = "Medio";
    break;
  case '3':
    $dificuldade = "Dificil";
    break;
}

switch ($rodada) {
  case '1':
    $rodada = "10";
    break;
  case '2':
    $rodada = "15";
    break;
  case '3':
    $rodada = "20";
    break;
}
    try{
     $conexao = new PDO ("mysql:host=localhost; dbname=teocratico; charset=utf8","root","");
     } catch (PDOException $erro){
       echo $erro->getmessage();
       //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
     }


$consulta = $conexao -> query ("SELECT id_pergunta, pergunta, resposta, desafio FROM perguntas
where dificuldade ='$dificuldade' ORDER BY rand() LIMIT $rodada ");
    // Mostrando a Consulta
        $consulta->fetch(PDO::FETCH_ASSOC);
        $db_data = $consulta->fetchAll(PDO::FETCH_ASSOC);
        json_encode($db_data);
        header('Location: '.'jogo.php');//Me joga para a pagina do jogo

?>

Jquery / Ajax

function randomizar(valor) {
     return Math.floor((Math.random() * valor) + 1);
   }
   //  data = [];
     //data.push({ name: "dificuldade", value: document.getElementById("dificuldade").value});
     //data.push({ name: "quantidade", value: document.getElementById("quantidade").value});
     jQuery.ajax({
         url: "dados_jogo.php",
         type: "POST",
         dataType: 'json',
         success: function(returnjson) {
             var elemento = returnjson[(randomizar(returnjson.length)-1)];
             var arr = [];
             arr = returnjson;
      var arr = [];
     function exibir(){
         var elemento = arr[(randomizar(arr.length)-1)];
         document.getElementById("id_pergunta").innerHTML =      elemento.id_pergunta;
         document.getElementById("pergunta").innerHTML = elemento.pergunta;
         document.getElementById("desafio").innerHTML = elemento.desafio;
         document.getElementById("resposta_jogo").value = elemento.resposta;
     },
         error: function(returnjson) {
             alert("erro interno do servidor");

         }
     });
    
asked by anonymous 28.01.2017 / 01:45

1 answer

1

You said it has three pages: 1-Index 2-dice.php 3-jogo.php

There we have 3 codes: 1- Index 2 - ConfP.PHP 3 - Jquery / Ajax

This makes it difficult to understand your problem. But let's go. The Config.php is the game.php data, and if I understand correctly, it is the one that you "get" via ajax. Come on: To generate a json to get caught by jquery you do not need the header. You're doing page redirection on the page that calls via ajax, which is probably the cause of the "Internal Server Error" error. Explaining, you submit an ajax request and page responds with the content data. No more work, no redirection. Treating this is simple, just redirect the page in the javascript using a location.href < link >

Maybe you do not even need ajax, a simple post request that redirects to another page is enough ...

    
28.01.2017 / 02:40