I make a feedback form, the script itself and the handler for the form found on the Internet. Here they are:

<script> // этот участок кода нужен только для отображения гифки // которая даёт пользователю понять, что что-то происходит // и нужно подождать $(document).ready(function () { $(document).ajaxStart(function () { // найдем элемент с изображением загрузки и уберем невидимость: var imgObj = $("#load-indicator"); imgObj.show(); // вычислим в какие координаты нужно поместить изображение загрузки, // чтобы оно оказалось в серидине страницы: var centerY = $(window).scrollTop() + ($(window).height() + imgObj.height()) / 2; var centerX = $(window).scrollLeft() + ($(window).width() + imgObj.width()) / 2; imgObj.offset({ left: centerX, top: centerY }); }); //скрываем изображение после окончания AJAX-запроса $(document).ajaxStop(function () { $('#load-indicator').hide(); }); }); // назначаем действие на такое событие как отправка формы $('#feedback').submit(function (evtObj) { evtObj.preventDefault(); // Если элемент формы fileforsending содержит значения (т.е. выбран файл для отправки), // то вместо AJAX-запроса используем FormData() // поскольку файлы через AJAX-запросы не передаются if (document.getElementById("feedback").fileforsending.value !== '') { //показываем гифку ожидания var imgObj = $("#load-indicator"); imgObj.show(); var centerY = $(window).scrollTop() + ($(window).height() + imgObj.height()) / 2; var centerX = $(window).scrollLeft() + ($(window).width() + imgObj.width()) / 2; imgObj.offset({ left: centerX, top: centerY }); // этот кусок кода я спёр отсюда http://javascript.ru/forum/jquery/40698-ajax-i-otpravka-fajjlov-s-formy.html var form = document.forms.feedback; var formData = new FormData(form); var xhr = new XMLHttpRequest(); xhr.open("POST", "mails_sender.php"); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { data = xhr.responseText; $("#result").html('Результат выполнения: ' + data); // Письмо отправлено, сбрасываем данные формы если прошло успешно if (data === 'Отправлено письмо с вложениями.') { document.getElementById("feedback").reset(); } //убираем гифку ожидания $('#load-indicator').hide(); } } }; xhr.send(formData); // В противном случае (не прикреплён файл для отправки) // Делаем AJAX-запрос для отправки письма } else { var form = $(this); $.ajax({ // Здесь файл, который обрабатывает полученные от пользователя данные и отправляет почту url: 'mails_sender.php', type: 'POST', data: form.serialize(), // Действия в случае успешной отправки AJAX-запроса (а не письма!) // Здесь data - полученное от mails_sender.php сообщение success: function (data) { if (data === 'Отправлено письмо без вложений.') { $("#result").html('Отправлено письмо без вложений.'); // Письмо отправлено, сбрасываем данные формы document.getElementById("feedback").reset(); // Следующая строка после успешной отправки сообщения // перенаправляет пользователь на любую страницу/сайт // достаточно раскомментировать её и поменять адрес сайта webware.biz // на ваш собственный //document.location.href = 'http://webware.biz'; } else { $("#result").html(data); } }, error: function (data) { $("#result").html('Результат выполнения: ' + data); } }); } }); </script> 
  <div style="color: red;" id="result">some text</div><br /> <img src="ajax-loader.gif" id="load-indicator" alt="loading" style="position:absolute; z-index:1000; display:none;" /> <h2>Форма обратной связи</h2> <form method="post" action="mails_sender.php" id="feedback" name="feedback" enctype="multipart/form-data"> <table style="width: 100%"> <tr> <td style="width: 146px">Ваш e-mail</td> <td><input name="youremail" type="text" style="width: 440px" size="20" /></td></tr> <tr> <td style="width: 146px">Тема сообщения</td> <td><input name="subject" type="text" style="width: 440px" size="20" /></td></tr> <tr> <td>Телефон:</td> <td> <input type="text" name="phone" style="width: 440px" size="20"> <tr> <td style="width: 146px">Ваше сообщение</td> <td> <textarea name="message" style="width: 440px; height: 130px" rows="1" cols="20"></textarea></td></tr> <tr> <td style="width: 146px">Ваше имя</td> <td><input name="name" type="text" style="width: 440px" size="20" value="" /></td></tr> <tr> <td style="width: 146px">Вы можете присоединить необходимые файлы</td> <td><input name="fileforsending" type="file" style="width: 440px" /></td></tr> <tr> <td style="width: 146px">&nbsp;</td> <td><br /> <input name="Reset1" type="reset" value="Очистить" style="width: 97px" /> <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name="Submit1" type="submit" value="Отправить" style="width: 157px" /> &nbsp; </span> </td></tr> </table> </form> 

But the problem is that the form identifier is used in the script to use the form, and they are supposed to be somewhat albeit absolutely identical on the page, and since the identifier must be only one data will be sent from only one form.

I tried to replace the document.getElementById(feedback) construct with such a document.getElementsByClassName(feedback) but didn’t succeed, I suppose because of this line here var form = document.forms.feedback; In it, the form variable is assigned some functions, but unfortunately I can’t understand what it is and what it is responsible for.

Tell me how you can modify the script so that you can send data from any form on the page?

  • It is not clear about duplicate forms. Can it be more extensively? Perhaps the question is to adjust the construction of the page. - Dan Irkutskiy
  • About document.getElementsByClassName (feedback). 1) feedback is variable? If not, document.getElementsByClassName ("feedback"). 2) I don’t see elements with the attribute class = "feedback" in the code. In general, this attribute is not used in the code. - Dan Irkutskiy
  • var form = document.forms.feedback; // The form variable is assigned a form object with the name = "feedback" attribute - Dan Irkutskiy
  • @DanIrkutskiy In general, on the same page there are several identical forms in different places, and all of them cannot be with the same identifier, the same is prohibited by the specification. - Constantine Shibaev
  • @DanIrkutskiy I apparently deleted the feedback class from the code (it must be assigned to the form itself), I will try to test it with your hint. And the last thing, if you replace document.getElementById (feedback) with document.getElementsByClassName ("feedback"), won't this cause an error here - var form = document.forms.feedback; ??? - Constantine Shibaev

0