Отправка формы XMLHttpRequest send form field
XMLHttpRequest send form field JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
document.addEventListener("DOMContentLoaded", function() { // Подключаем скрипт При полной загрузке сайта document.getElementById('upload').onclick = function() { // Событие на клик кнопки var req = new XMLHttpRequest(); var formSend = new FormData(); req.open("POST", '/testjs/handler.php'); obj = { 'Ключ 1' : 'Значение 1', 'Ключ 2' : 'Значение 2' }; for (key in obj){ formSend.append(key, obj[key]); } form = document.forms.test_send; for (var i = 0; i <= (form.length - 1); i++){ value = form[i].value; name = form[i].name; if (value){ formSend.append(name, value); } } req.onreadystatechange = function() { if (req.readyState == 4) { request = req.responseText; console.log(request); document.getElementById('consoleLog').innerHTML = request; } } req.send(formSend); return false; } }); |
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test js</title> <link rel="stylesheet" type="text/css" href="/testjs/style.css" /> <script type="text/javascript" src="/testjs/custom.js"></script> </head> <body> <form method="POST" id="test_send" enctype="multipart/form-data"> <input type="text" name="field1"><br /> <input type="text" name="field2"><br /> <input type="submit" value="Отправить" id="upload"> </form> <hr> <div id="consoleLog"></div> </body> </html> |
PHP
1 2 |
<?php var_dump($_REQUEST); |