Отправить с текущей формы ajax запрос
У меня есть таблица с множеством форм. Вот мой код:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>LastName</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr th:if="${records.empty}">
<td colspan="5"> No Records Available </td>
</tr>
<tr th:fragment="entity-row" th:each="record : ${records}">
<form id="subscription_order_form" th:action="@{/changeElementTable}" method="post">
<td><input th:value="${record.id}" name="id" ></td>
<td><input th:value="${record.firstName}" id="firstName" name="firstName" ></td>
<td><input th:value="${record.lastName}" id="lastName" name="lastName" ></td>
<td><input th:value="${record.phoneNumber}" id="phoneNumber" name="phoneNumber" ></td>
<td><input th:value="${record.email}" id="email" name="email" ></td>
<td><input th:value="${record.id}" id="idRepeat" type="hidden" name="idRepeat" ></td>
<td><button id="button">Отправить</button></td>
</form>
</tr>
<tr></tr>
<th></th>
</tbody>
</table>
<script>
$("#subscription_order_form").submit(function(e) {
e.preventDefault();
editAjax();
})
function editAjax() {
$(':input').removeAttr('readonly');
var form_data = $('#subscription_order_form').serialize();
$.ajax({
url : '/changeElementTable',
type: 'POST',
data:form_data,
success : function(responce) {
},
error : function(){
alert("error");
}
});
}
</script>
Но у меня данные отправляются сразу со всех форм на бэкенд. Как сделать чтобы данные отправлялись с той формы где стоит курсор на любом из её инпутов ?
Ответы (1 шт):
Автор решения: Slava Ivanov
→ Ссылка
Не уверен если вам до сих пор нужен ответ, но как-то так...
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// make sure the code runs after page loaded
$(function() {
$("button:button").on("click", function(e) {
e.preventDefault();
var currentForm = $(this).parents('form');
var currentRow = $(this).parents('tr');
$.ajax({
url: currentForm.prop('action'),
type: currentForm.prop('method'),
data: currentRow.find('input').serialize(),
success: function(responce) {
},
error: function(){
alert("error");
}
});
});
});
</script>
</head>
<body>
<form th:action="@{/changeElementTable}" method="post">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>LastName</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<!--/*/
<tr th:if="${records.empty}">
<td colspan="5"> No Records Available </td>
</tr>
/*/-->
<tr th:fragment="entity-row" th:each="record : ${records}">
<td><input th:value="${record.id}" name="id"></td>
<td><input th:value="${record.firstName}" name="firstName"></td>
<td><input th:value="${record.lastName}" name="lastName"></td>
<td><input th:value="${record.phoneNumber}" name="phoneNumber"></td>
<td><input th:value="${record.email}" name="email"></td>
<td><input th:value="${record.id}" type="hidden" name="idRepeat"></td>
<td><button type="button">Отправить</button></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
По порядку:
- версия JQuery вы использовали очень старая; используйте новою.
- убедитесь код запускается только когда страница загружена
- просто добавте один обработчик на все кнопки
- используйте родителей кнопки которая нажата
- вам не нужна HTML форма в цикле
- не используйте
idHTML атрибут в цикле
