Pedidos POST

Os pedidos POST devem ser usados sempre queremos enviar dados de um formulário ou se quisermos enviar um maior volume de dados em segurança.

Exemplo:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial
scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
    <title>AJAX POST</title> 
    <script> 
        var xhr=new XMLHttpRequest(); ;  
 
        function gravar(){ 
 
            //obtem os dados do formulario: 
            var nome = document.getElementById('nome').value; 
            var morada = document.getElementById('morada').value; 
            var turma = document.getElementById('turma').value; 
 
            //define string com os dados: 
            var dados = 'nome=' + nome + '&morada=' + morada + '&turma=' + turma; 
 
            //parametriza xhr para um pedido POST:
                xhr.onreadystatechange = function(){ 
                if (xhr.readyState == 4 && xhr.status == 200) { 
                    var msg = xhr.responseText; 
                    document.getElementById('msg').innerHTML = msg; 
                } 
            } 
            xhr.open("POST", "createAluno.php", true); 
            xhr.setRequestHeader("Content-type", "application/x www-form-urlencoded"); 
            //Envia os dados para o servidor:
            xhr.send(dados); 
        } 
    </script> 
</head> 
<body> 
    <h2>Registo de alunos</h2> 
    <br> 
    <form> 
        Nome: <input type="text" name="nome" id="nome"><br> 
        Morada: <input type="text" name="morada" id="morada"><br> 
        Turma: <input type="text" name="turma" id="turma"><br> 
        <br></br> 
        <input type="button" value="Gravar" onclick="gravar()"> 
        <p id="msg" style="color: red; text-align: center"></p> 
    </form> 
</body> 
</html>

Exemplo 2:

Neste exemplo, chama um script de PHP (createAlunoJson.php) envia dados de um aluno no formato JSON

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      var xhr = new XMLHttpRequest();

      function showAluno() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          //alert(xhr.responseText);
          const aluno = JSON.parse(xhr.responseText);
          const div = document.getElementById("show");
          div.innerHTML = aluno.nome + " - " + aluno.turma;
        }
      }

      function criarAluno() {
        const aluno = {
          nome: "Ricardo",
          turma: "165",
        };
        //define a função que vai receber e tratar a resposta:
        xhr.onreadystatechange = showAluno;
        //define o pedido:
        xhr.open("POST", "createAlunoJson.php", true);
        // Content-Type header : JSON :
        xhr.setRequestHeader("Content-Type", "application/json");
        //envia o pedido:
        xhr.send(JSON.stringify(aluno));
      }
    </script>
  </head>
  <body>
    <div id="show"></div>
    <hr />
    <button onclick="criarAluno()">Criar aluno</button>
    <script>
      const bt = document.getElementById("bt");
    </script>
  </body>
</html>