Bootstrap Modal Popup Form Submit With Ajax And Laravel

5 min read Jul 02, 2024
Bootstrap Modal Popup Form Submit With Ajax And Laravel

Bootstrap Modal Popup Form Submit with AJAX and Laravel

This article will guide you through creating a Bootstrap modal popup form that submits data to your Laravel backend using AJAX. This approach provides a user-friendly experience by allowing form submission without full page reloads, enhancing your web application's responsiveness.

1. Setting Up the Modal

First, let's create the Bootstrap modal HTML structure. This example will showcase a simple "Contact Us" form:


2. Implementing AJAX Form Submission

Now, let's add the JavaScript code to handle the form submission via AJAX:

$(document).ready(function() {
  $('#contactForm').submit(function(event) {
    event.preventDefault(); 

    $.ajax({
      url: "{{ route('contact.store') }}", // Replace with your Laravel route
      type: "POST",
      data: $(this).serialize(),
      success: function(response) {
        // Handle success response
        // You can show a success message to the user
        alert("Your message has been sent!");
        $('#contactModal').modal('hide');
        $('#contactForm')[0].reset();
      },
      error: function(error) {
        // Handle error response
        // Display an error message to the user
        alert("Something went wrong. Please try again later.");
      }
    });
  });
});

3. Laravel Controller and Route

Finally, we need to create a controller in Laravel to handle the AJAX request.

Create a new controller:

php artisan make:controller ContactController

Add the following code to your ContactController:

validate([
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
        ]);

        // Process the form data (e.g., save to database)
        // ... 

        // Return a success response (optional)
        return response()->json([
            'success' => true,
            'message' => 'Your message has been sent successfully.'
        ]);
    }
}

Register the route in routes/web.php:

Route::post('/contact', [ContactController::class, 'store'])->name('contact.store');

Conclusion

This setup allows users to submit contact forms directly from the modal without refreshing the entire page. This significantly enhances the user experience. Remember to customize the code according to your application's specific requirements.

Latest Posts


Featured Posts