Nov 25, 2024
0
Level 2
Laravel with SweetAlert2: Form Submission Issues
Hi everyone,
I’m working on a Laravel project and using SweetAlert2 to display a success alert when a form is submitted successfully. Here’s my current setup:
Form Layout:
<form method="POST" action="{{ route('reg.store') }}" id="RegistrationForm">
@csrf
<x-forms.field-container class="sm:col-span-4">
<x-forms.label for="first_name">
First Name <span class="text-red-500">*</span>
</x-forms.label>
<x-forms.input
type="text"
id="first_name"
name="first_name"
:value="old('first_name')"
autocomplete="off" />
<x-forms.error name="first_name" />
</x-forms.field-container>
</form>
Store Method in Controller:
public function store(Request $request)
{
$validatedData = $request->validate([
'first_name' => ['required', 'string', 'max:255'],
'middle_name' => ['nullable', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
]);
return response()->json([
'success' => true,
'message' => 'Registration successful.',
], 201);
}
SweetAlert2 Script:
<script>
const form = document.querySelector('#RegistrationForm');
form.addEventListener('submit', async (e) => {
e.preventDefault(); // Problem here
const formData = new FormData(form);
try {
const response = await fetch(form.action, {
method: 'POST',
body: formData,
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
},
});
const result = await response.json();
if (result.success) {
Swal.fire({
title: 'Pre-registration Successful!',
text: 'You have successfully registered. Click OK to view further instructions.',
icon: 'success',
confirmButtonText: 'OK',
customClass: {
confirmButton: 'bg-primary text-white px-6 py-3',
},
}).then(() => {
window.location.href = "{{ route('login') }}"; // Redirect to login page
});
} else {
Swal.fire({
title: 'Error!',
text: result.message || 'An error occurred. Please try again.',
icon: 'error',
});
}
} catch (error) {
Swal.fire({
title: 'Error!',
text: 'Something went wrong. Please try again later.',
icon: 'error',
});
}
});
</script>
The Problem
- If I include e.preventDefault(); in my script, it prevents Laravel from displaying the validation errors in the <x-forms.error> component.
- If I remove e.preventDefault();, the form submits properly, and Laravel displays the errors, but when the form is successful, it only returns the JSON response, and SweetAlert2 doesn't trigger.
What I Want to Achieve
- Display the validation errors in the <x-forms.error> component when the form fails validation.
- Show a SweetAlert2 success message when the form submission is successful.
Has anyone encountered this issue before or knows how to resolve it? How can I display both Laravel validation errors and the SweetAlert2 success message effectively?
Thanks in advance!
Please or to participate in this conversation.