Update PHP variable with Jquery using AJAX request

Asked

Viewed 484 times

1

I have a problem related to HTML, Jquery and PHP, I will try to pass the most information. I have a PHP page that has to go back and forth with variables and it’s like a step by step, where each step sends its data to the next to filter the tables in the Mysql database. My problem is the variable goes but doesn’t come back. So I am including in the project AJAX requests, where when I click the button I send to the same page via POST in Jquery the values. The problem is that the variable is not taking this value. Could I set this variable after clicking on the button, or pass this value in another way? I will send the codes.

console.log($("#prox1"));


$("#prox1").click(function(event) {
console.log("Ok");
console.log($("#curso").val());
console.log($("#turno").val());
console.log($("input[name='tipoLab']:checked").val());
  var dados1 = {curso: $("#curso").val(), turno: $("#turno").val(), tipoLab: $("input[name='tipoLab']:checked").val()};

  $.post('../processamento/index.php', dados1, function() {
    console.log("Fui e voltei");
  });
});
<div class="ls-steps-content" id="step1">
            <?php $sql ="SELECT cursos from cursos order by cursos asc";
            $resultado = conecta( $maquina , $usuario, $senha, $banco, $sql );?>
            <div class="ls-custom-select selectEtapa1">
              <select id="curso" name="curso" class="ls-select">
                <option selected="selected" disabled="disabled"> Cursos </option>
                <?php while ($row = mysql_fetch_assoc($resultado)) {
                  $curso = $row["cursos"];
                  ?>
                  <option value="<?=$curso?>"><?=$curso?></option>
                  <?php } ?>
                </select>
              </div>
              <div class="ls-custom-select selectEtapa1">
                <select id="turno" name="turno" class="ls-select">
                  <option selected="selected" disabled="disabled"> Turno </option>
                  <option value="Manha"> Manhã </option>
                  <option value="noite"> Noite </option>

                </select>
              </div>
              <fieldset>
                <!-- Exemplo com Radio button -->
                <div class="ls-label col-md-5">
                  <p>Escolha uma das plataformas:</p>
                  <label class="ls-label-text">
                    <input type="radio" name="tipoLab" value="labinfo">
                    Laboratório de informática
                  </label>
                  <label class="ls-label-text">
                    <input type="radio" name="tipoLab" value="labEng">
                    Laboratorio de Engenharia
                  </label>
                  <label class="ls-label-text">
                    <input type="radio" name="tipoLab" value="labSau">
                    Laboratório de Saúde
                  </label>
                </div>
              </fieldset>
              <div class="ls-actions-btn">
                <form method="post" action="index.php">
                  <input type="hidden" name="curso">
                  <button type="submit" id="prox1" href="#" class="ls-btn-primary ls-float-right" data-action="next">Próximo</button>
                </form>
              </div>
            </div>
            <div class="ls-steps-content" id="step2">
              <?php $_POST["curso"] ?>
              <div class="ls-actions-btn">
                <a href="#" class="ls-btn" data-action="prev">Anterior</a>
                <a href="#" class="ls-btn-primary ls-float-right" data-action="next">Próximo</a>
              </div>
            </div>

If someone has another way to help me it can be too, I just need to keep going back and forth with these variables when the user wants.

Thanks in advance

  • I believe the error is when taking this data and not in sending

  • which variable are you passing by? where it should return?

  • Should it return in this section <div class="ls-Steps-content" id="step2"> <?= $_POST["course"] ? > Since I sent her via POST to the same page in AJAX, in Inspector, I went to the Network and there are the parameters of the POST so I do not know why she is not receiving the same.

1 answer

1


I will try to be brief with the answer. I see some errors that are preventing the correct functioning:

  • The page is being up-to-date when making the AJAX request. To avoid this in the function callback of Event Handler click(), add the code event.preventDefault(), for the event click is being triggered by a button submitof a form.
  • If you are receiving a JSON response, you need to include "post" as quarter function parameter post()
  • About "O meu problema é que a variável vai mas não volta.", just to be clear if this is your question too: the variable does not return. What will return is a new value (which can be equal to the sent) sent by the page invoked - in this case ../processamento/index.php. But it doesn’t make much sense to return the same value since you already have this value in jQuery. It’s faster just return a success message.
  • I’m not sure I understand, but "onde ao eu clicar no botão eu mando para a mesma página via POST" i understood that you are sending the request to the same form page. If this is correct, what will be returned by the server will be the same html page that makes the order (without the changes made by the user). But if you want to return only "simple" data, you can return this data in JSON by PHP - or even otherwise.

I always think it good to convert the data with JSON.stringfy(meusDados) before sending them to the server, because PHP has some restrictions when working with JSON. To quote some of the PHP documentation:

  • Names and values string must be in double quotes. Ex: '{"nome": "valor", "idade": 32}'
  • Cannot have a comma after the last item. Ex: '{"vouDarErro":"vírgulaSobrando",}'

I hope I’ve helped. If you’re confused, comment below.

  • Let me try to be more clear, I have a Trial Scheduling system right? On the first page I get the Course, Shift and Lab Guy. What I want is to take the values that were chosen to make a SELECT in Mysql of the rooms of the type of chosen laboratory understood? So I need these 3 values to be stored in a PHP variable that I can use on the same page to start doing my searches in the database. Ex.: values = typeLab: "Labinfo"; <? php $Tipolab = $_POST["typeLab"]; $sql = "SELECT salas FROM Labs WHERE typeLab = '$Tipolab'"; This on the same page

  • You want to order via AJAX for the same PHP page that contains the form?

  • This, if possible without having to reload, but if necessary and better than nothing kk

  • The function of AJAX is to ask for resources (pages, data, images, etc.) asynchronously, i.e., "without updating the page". However, in your case, I don’t think it makes sense to allow PHP to return the same page that contains the entire form. Because then the PHP server will render the page and return an HTML that will be equal to the page you are already on (except the data you are loading from the BD). What you want is just the new comic book data. Summarizing, in your case, the return of the AJAX request should return only the new data and not the whole HTML page again

  • You can create a if at the beginning of your PHP file that checks whether data is being received. If yes, instead of running the page normally, it runs only the code block of that if. But I think you’d better use another page to fetch the PHP data because it only needs to return the new data (not the HTML structure of the page). Maybe this post will help you: https://answall.com/questions/297033/como-salvar-no-mysql-todo-dado-inseriado-em-um-form-control/297125#297125

Browser other questions tagged

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