Pedidos PUT

Os pedidos PUT são usados sempre que pretendemos enviar dados para atualização.

Exemplo 1:

<!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>Update aluno</title>
    <script>
      var xhr = new XMLHttpRequest();

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

      function updateAluno(event) {
	//Interrompe a submissão do formulário:
	event.preventDefault();
        //Obtém os dados do formulário:
        const nome = document.getElementById("nome");
        const turma = document.getElementById("turma");
	//Constrói os dados a enviar no formato form-urlencoded:
        const aluno = "nome=" + nome + "&turma=" + turma;
        //define a função que vai receber e tratar a resposta:
        xhr.onreadystatechange = showAluno;
        //define o pedido:
        xhr.open("PUT", "updateAluno.php", true);
        xhr.setRequestHeader(
          "Content-type",
          "application/x-www-form-urlencoded"
        );
        //envia o pedido:
        xhr.send(aluno);
      }
    </script>
  </head>
  <body>
    <hr />
	<form>
	    Nome: <input type="text"  id="nome" value="Pedro"><br>
		Turma: <input type="text"  id="turma" value="165"><br>
		<button onclick="updateAluno(event)" >
          Submeter
        </button>
	</form>
    <script>
      const bt = document.getElementById("bt");
    </script>
  </body>
</html>

No exemplo obtemos os dados de um aluno de um formulário, enviamos esses dados num pedido PUT assíncrono para o script updateAluno.php, no servidor, que irá atualizar os dados na base de dados e envia, por JSON, o objeto aluno atualizado.

Exemplo 2:

<!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>Update aluno</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 + " - aluno alterado";
        }
      }

      function updateAluno(event) {
	//Interrompe a submissão do formulário:
	event.preventDefault();
 	//Obtém os dados do formulário:
        const nome = document.getElementById("nome");
	const turma = document.getElementById("turma");

        //define a função que vai receber e tratar a resposta:
        xhr.onreadystatechange = showAluno;
        //define o pedido:
        xhr.open("PUT", "updateAlunoJson.php", true);
        // Content-Type header : JSON :
        xhr.setRequestHeader("Content-Type", "application/json");

        //envia o pedido, convertendo os dados para o formato JSON:
        xhr.send(JSON.stringify(aluno));
      }
    </script>
  </head>
  <body>
    <div id="show"></div>
    <hr />
 	<form>
	    Nome: <input type="text"  id="nome" value="Pedro"><br>
		Turma: <input type="text"  id="turma" value="165"><br>
		<button onclick="updateAluno(event)" >
          Submeter
        </button>
	</form>
    <script>
      const bt = document.getElementById("bt");
    </script>
  </body>
</html>

O exemplo acima é igual ao Exemplo 1 com a diferença que os dados são enviados para o servidor no formato JSON.