Catch a PHP JSON Via Jquery

Asked

Viewed 603 times

0

I have 3 pages, 1-Index, where I pass some settings; 2- data_game.php, where you query and return a json with the dice; 3- game.php, The page where the json data is displayed are displayed.

My difficulty now is, to take this Json data generated by PHP, I think they are getting lost when I give the Header to the other pag, how do I handle it better? Here is returned the "Internal Server Error", there is some way for me to check 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");

         }
     });
  • You cannot redirect the object output JSON. Use header('Location: '.'jogo.php'); is wrong. If you need to redirect, you have to redirect to JavaScript. After all, what exactly is this redirect for, huh? It’s simple: Your JavaScript is waiting for an object JSON. If you redirect, the answer from PHP will never be an object JSON, nor success:.

  • This redirect probably causes the error,"Internal Server Error"

1 answer

1

You said it has three pages: 1-Index 2-dados_game.php 3-game.php

There are three codes: 1- Index 2 - Config.PHP 3 - Jquery/Ajax

This makes it difficult to understand your problem. But come on. Config.php is the.php data_game, and if I understand correctly, it’s what you "get" by ajax. Come on, let’s go: To generate a json to get caught by jquery you don’t need the header. You are making the page redirection on the page that called via ajax, probably this is the cause of the error "Internal Server Error". Explaining, you send an ajax request and page responds with the content data. It ends there the work, there should be no redirection. Treating this is simple, just redirect the page in javascript, using a Location.href <http://www.w3schools.com/jsref/prop_loc_href.asp>

Maybe you don’t even need ajax, a simple post request that redirects to another page will be enough...

  • I use Header, because if I don’t use all the action for in.php data_game, it displays JSON and so on, you mean then I have to redirect using another language? Could I give you an example, please?

  • I don’t understand why you use the header. Another language, javascript, you redirect in the client-side.

Browser other questions tagged

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