Save data from a query to an array and display it via JQuery

0

I'm doing a question and answer game, I need to make an appointment in the bank and I'll get 4 columns (id, question, answer and challenge) and it will return me 10, 15 or 20 lines depending on what is chosen by the user. After that, these columns would be displayed in each DIV of my HTML, every time the user clicks the switch button, it goes to the next line.

I thought of writing these queries in an array and fetched via JavaScript, but I honestly do not know how to do that. Could someone help me?

HTML INDEX (Where settings are passed from the game):

  <form id="jogo" action="dados_jogo.php" Method="POST">
                <div class="input-group">
                 <span class="input-group-addon" id="equipe1"><img src="img/nome.ico"></span>
                   <input type="text" 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" id="equipe2"><img src="img/nome.ico"></span>
                  <input type="text" class="form-control" placeholder="Nome da Segunda Equipe" aria-describedby="basic-addon1">
                   </div>
                   <br>
                   <div class="valida 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>

Function that I'm trying to develop to validate this form and play for my php action:

$(function () {
$('#refresh').click(function () {
    window.location = window.location;
});
          // Comportamento do botao de envio do FORM
          $('#iniciar').click(function () {
              if(validar() === true){
                  // Se a validacao passar, carrega os dados do FORM e envia
                  $.post(
                      $("#form_jogo").attr("action"),// Captura o ACTION do FORM
                      $("#form_jogo").serialize() // Captura os campos do FORM
                  )
                  // Se enviar com sucesso, retorna a resposta do PHP
                  .done(function () {
                    //Se o post para o php for com sucesso ele vai executar a merda toda
                    //e vai me levar pra pagina do jogo com os dados inseridos aqui no index

                  })
                  // Se o envio falhar, retorna uma msg de erro
                  .fail(function (resp) {
                    //Se der erro ele só vai mudar a classe da div e dizer que não conseguiu
                      $("#success").attr('class','alert alert-danger'); //Muda o CSS da DIV
                      $("#success").html('Não foi possível iniciar o jogo!'); //Preenche a DIV com a msg
                      $('#tentar').show(); //Mostra a DIV
                      $
                  });
              } else {

              }
          });
      });
      // Validacao do FORM ao enviar
      function validar() {
          var passou = true;
          if ($('#equipe').val() === "") {
              $('#valida_equipe').show();
              passou = false;
          } else {
              $('#valida_equipe').hide();
          }
          if ($('#equipe2').val() === "") {
              $('#valida_equipe2').show();
              passou = false;
          } else {
              $('#valida_equipe2').hide();
          }
          return passou;
      }

PHP code, I need to query and return in an array (OR store the N Questions somehow, so I can retrieve it later.)

     <?php

$equipe1 = $_POST['equipe1'];
$equipe2 = $_POST ['equipe2'];
$dificuldade = $_POST ['dificuldade'];
$rodada = $_POST ['rodada'];

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){
   header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true,     500);
 }


   //AGORA EU PRECISO FAZER A CONSULTA E ARMAZENA-LA NUM ARRAY PARA PASSAR AS INFORMAÇÕES PARA OUTRA PAG.
}


?>

HTML WHERE ARE THE INFORMATION FILLED IN INDEX AND WHERE THE SELECTED FIELDS WILL APPEAR:

     <div class="container">
   <div class="row">
   </div>
   <div class="row">
     <div class="col-md-6 col-md-offset-3">
        <div class="page-header text-center">
          <h2><span class="glyphicon glyphicon-th"></span>&nbsp;Que os jogos comecem</h2>&nbsp;
        </div>
     </div>
   </div>
   <div class="row">
     <div id="pergunta_jogo" class="col-md-6 col-md-offset-3">
       <div class="alert alert-info">
         <!--ID da pergunta!--><h3>(XXXXXX)</h3>
         <h2><span class="glyphicon glyphicon-question-sign"></span>&nbsp;Aqui vão aparecer as perguntas</h2>
      </div>

    </div>
  </div>
  <div class="row">
    <div id="resposta_jogo" class="col-md-6 col-md-offset-3">
      <div class="alert alert-success">
        <h2><span class="glyphicon glyphicon-ok"></span>&nbsp;Aqui vai aparecer a resposta</h2>
      </div>

    </div>
  </div>
  <div class="row">
    <div id ="desafio_jogo"class="col-md-6 col-md-offset-3">
      <div class="alert alert-danger">
      <h2><span class="glyphicon glyphicon-remove "></span>&nbsp;Aqui vai aparecer o desafio</h2>
      </div>

    </div>
  </div>
</div><br />
  <div class="container"><!--Ajustar a posição com media query depois!-->
    <div class="row">
      <div class="col-md-6 ">
        <div class="page-header"><!--Nome da equipe e pontos!-->

          <!--Nome da equipe e pontos!--><h3>Nome equipe1 <span id ="ponto1"class="label label-info">X</span></h3>
        </div>
        <input type="button" class="btn btn-danger" role="button" value="Passar" id="passar1" />
        <input type="button" class="btn btn-success" role="button" value="Acertar" id="acertar1" />
      </div>
    </div>
      <div class="row">


      <div class="col-md-6 text-right ">
        <div class="page-header" id="equipe2">

        <!--Nome da equipe e pontos!--> <h3>Nome equipe2 <span id ="ponto2" class="label label-info">X</span></h3>
        </div>
        <input type="button" class="btn btn-danger" role="button" value="Passar" id="passar2" />
        <input type="button" class="btn btn-success" role="button" value="Acertar" id="acertar2" />
      </div>
</div>
</div>
    
asked by anonymous 09.01.2017 / 20:20

1 answer

1

You have to know JQuery . You have to know, minimally, the syntax of the language ( JavaScript ) and the library. You need to know that to reference an element, you must use a selector . See: $('#form') is selecting the form by id.

In the example, I want to send form without refresh , so I first used the preventDefault() method to avoid default behavior. So, when I click the Submit button, the form does not generate a request , and the page does not update:

$("#form").submit(function (e) {
 e.preventDefault();
});

Then I had to send the data from form via POST to the test.resp.php script, so I used the method $.post reporting url and data to send [where: $.post(url, data) referrals ]:

$("#form").submit(function (e) {
 e.preventDefault();
 $.post( $("#form").attr("action"), $("#form").serialize() )
});

If you analyze the code and look up information from api documentation, you'll find out what each method used in the program is for. You will find, for example, that $("#form").serialize() passed as data is transforming the fields of $("#form") into a string to be able to submit data without refresh .

It's no use starting off for development if you do not understand what the library is doing.

I suggest you study the code I posted in this answer with the help of the browser console. I guarantee that after learning what is happening with this program you will be able to do what you want in yours.

test.php :

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js"integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <style>
            body{
                margin-top: 20px;
            }
            #callback{
                display: none;
            }
        </style>
        <script> 
            $(function () {
                //Comportamento do FORM ao ser enviado
                $("#form").submit(function (e) {
                    e.preventDefault();
                    $.post(
                        $("#form").attr("action"),
                        $("#form").serialize()
                    )
                    .done(function (resp) {
                        var obj = $.parseJSON(resp);
                        var string = '';
                        var divclass = $('#callback').attr('class');
                        $.each(obj, function(i, v) {
                            string += 'id: '+i+' email: '+v.valor+'<br>';
                        });
                        callback('success', string);
                    })
                    .fail(function (resp) {
                        callback('success', resp);
                    });
                });
            });

            //Funcao que modifica a DIV callback
            function callback(mode, string){
                var divclass = $('#callback').attr('class');
                if(mode === 'success'){
                    $('#callback').removeClass(divclass);
                    $('#callback').addClass('alert alert-success');
                    $('#callback').html(string);
                    $('#callback').show();                    
                }
                else{
                    $('#callback').removeClass(divclass);
                    $('#callback').addClass('alert alert-success');
                    $('#callback').html(string);
                    $('#callback').show();
                }
            }

        </script>
    </head>
    <body>
        <div class='container'>
            <form class="col-sm-6" id="form" action="test.resp.php">
                <div class="alert" id="callback"></div>
                <div class="form-group" id="form-group-email">
                    <label>Email address</label>
                    <input type="email" class="form-control" id="email" name="email" placeholder="Email">
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>          
        </div>
    </body>
</html>

test.resp.php :

<?php
//Suponha que a resposta da query seja esse array:
$resp = [
    0 => ['id'=>0,'valor'=>'Linha 1: '.$_POST['email']],
    1 => ['id'=>1,'valor'=>'Linha 2: '.$_POST['email']]
];
//Formatemos o array acima para um padrão legivel ao javascript.
//Aqui eu decidi que o php vai responder um objeto json, mas vc pode mandar
//qualquer coisa que o javascript possa manipular
echo json_encode($resp);
    
11.01.2017 / 16:11