receive data via jquery php for the same page

Asked

Viewed 26 times

-1

Hello, I have a question related to pass html values to php asynchronously I have a page entitled test.php this page has an input, where my goal is to take the value of this input and assign a php variable in the same page below.

My problem is this, when activating the click event jquery sends the value to the varialvel php but tbm duplicates the html part as I can solve this?

(Note: all this code is in one page: test.php)

<html>

<body>
  <div>
    <p>Nome</p>
    <input type="text" id="nome" name="nome" />
    <p>Idade</p>
    <input type="text" id="idade" name="idade" />
    <br />
    <input type="button" value="Send" id="botao" name="botao" />
    <br />
    <span id="resultado"></span>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    var nome = document.getElementById("nome");
    var idade = document.getElementById("idade");
    var botao = document.getElementById("botao");

    //evento dispara quando clicar
    botao.onclick = function() {
      processar(nome.value, idade.value);
    };

    function processar(nome, idade) {
      $.ajax({
          url: 'test.php',
          type: 'POST',
          data: {
            n: nome,
            i: idade
          },
          dataType: "html",
          beforeSend: function() {
            console.info("ENVIANDO...");
            $("#resultado").html("ENVIANDO...");
          }
        })
        .done(function(msg) {
          console.info("OK", msg);
          $("#resultado").html(msg);
        })
        .fail(function(jqXHR, textStatus, msg) {
          console.error("ERRO");
          alert(msg);
        });
    }
  </script>
</body>

</html>

PHP:

<?php
$nome = $_POST["n"];
$idade = $_POST["i"];

function EnviarMsg($n, $i){
    return "Olá {$n} sua idade é {$i}!";
}

echo EnviarMsg($nome, $idade);
?>
  • The page requested in Ajax (in this case, a .php page), must return only what you want to return, and not contain all the HTML, because the HTML tb is returned.

  • @Sam But there is no way to make this request to own? , page to update the value of a php variable for example.

  • Yes, it is possible, just use an if returning what you want if there is a request on the page.

  • cool, you would have some example to show me how it works?

  • your goal is to go to PHP even or just put the input value in HTML? Is that if you need to put only the input value do not need to ajax

  • @Alexisgarcia my goal is to go to PHP itself, and from there I would give an echo to show on the page

Show 1 more comment
No answers

Browser other questions tagged

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