Reputation: 285
I have a laravel project where admin can change user data via form. I want this form to be submitted by ajax. But it doesn't get submited.
I have a form:
<form id="userData{{$loop->iteration}}" method="POST">
@csrf
<!--some inputs-->
</form>
<button id="changeUserData{{$loop->iteration}}" data-id="#userData{{$loop->iteration}}">Save</button>
JS:
$("#changeUserData{{$loop->iteration}}").click(function (e) {
var ele = $(this);
var formId = ele.attr("data-id");
console.log(formId);
$(formId).submit(function (e){
console.log("test2");
e.preventDefault();
$.ajax({
url: '{{url('changeUserData')}}',
method: "PATCH",
data: $(formId).serialize(),
success: function(){
console.log("test");
}
})
})
});
When I press the button the first console.log gets fired but nothing else. I checked if formId matches the form id and it does so I don't know what's wrong.
Upvotes: 0
Views: 26
Reputation: 8340
The problem is .submit()
with handler
argument does not submit the form itself. It just binds an event handler to the form's submit
event.
You may just remove that bind and it should work:
$("#changeUserData{{$loop->iteration}}").click(function (e) {
var ele = $(this);
var formId = ele.attr("data-id");
console.log(formId);
$.ajax({
url: '{{url('changeUserData')}}',
method: "PATCH",
data: $(formId).serialize(),
success: function(){
console.log("test");
}
})
})
Upvotes: 2