-1

Недавно начал учить js. С xhr методом GET разобрался, а вот как через POST не пойму. Хотел вводить в первом input одно число, а во втором другое и просто их слаживать или умножать в php файле и получать результат в консоль например.

document.getElementById('getForm').addEventListener('submit', getAjax);

function getAjax(e) {
     e.preventDefault();

     var xhr = new XMLHttpRequest();

     xhr.open('POST', 'repeat.php', true);
     xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 & xhr.status == 200) {
               console.log(xhr.responseText);

          } else if (xhr.onerror == 404) {
               console.log('Error');

          }
     }
     xhr.send();
}
<!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>JS XHR</title>
</head>

<body>
     <form id="getForm" method="POST">
          <input type="text" name="one" id="one">
          <input type="text" name="two" id="two">
          <input type="submit" value="send">
     </form>
     <script src="./repeatajax.js"></script>
</body>

</html>

и php файл

<?php

echo 'Processing...';
echo $_POST['one'] *  $two = $_POST['two'];

1
  • вы ничего не отправляете на сервер, а просто открываете файл
    – Gs D
    25 фев 2018 в 18:33

1 ответ 1

1
document.getElementById('getForm').addEventListener('submit', getAjax);

function getAjax(e) {
     e.preventDefault();

     var xhr = new XMLHttpRequest();

     xhr.open('POST', 'repeat.php', true);
     xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 & xhr.status == 200) {
               console.log(xhr.responseText);

          } else if (xhr.onerror == 404) {
               console.log('Error');

          }
     }
     xhr.send(new FormData(e.target));
}
1
  • Спасибо, вышло.
    – Andrii
    25 фев 2018 в 18:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.