Laravel 6 - Ajax Form Submit with Custom Validation

Laravel 6 - Ajax Form Submit with Custom Validation


Laravel 6 - Ajax Form Submit with Custom Validation

In this guide, you'll learn how to submit a form using Ajax in Laravel 6, along with custom validation for form fields.

1. Set Up Your Laravel Project

Ensure that your Laravel project is set up properly. In case you're starting from scratch, you can create a new project using:

composer create-project --prefer-dist laravel/laravel laravel-ajax-form

2. Install jQuery

Since we are using Ajax for form submission, ensure that jQuery is available in your project.

You can include it by adding the following script to your resources/views/layouts/app.blade.php or the specific Blade file you're using for the form.

<!-- jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Alternatively, you can install jQuery via npm and include it in your webpack configuration.

3. Create Controller and Route

Generate a controller for handling form submissions:

php artisan make:controller AjaxFormController

In the app/Http/Controllers/AjaxFormController.php file, add the following code:

namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator; class AjaxFormController extends Controller { // Display the form public function index() { return view('ajax-form'); } // Handle Ajax Form Submission public function submitForm(Request $request) { // Custom Validation $validator = Validator::make($request->all(), [ 'name' => 'required|min:3', 'email' => 'required|email', 'age' => 'required|integer|min:18', ]); // Check validation if ($validator->fails()) { return response()->json(['errors' => $validator->errors()]); } // Process the valid data (you can save it to the database here) // For now, we return the success message. return response()->json(['success' => 'Form submitted successfully!']); } }

Next, define the routes in routes/web.php:

use App\Http\Controllers\AjaxFormController; Route::get('/ajax-form', [AjaxFormController::class, 'index']); Route::post('/ajax-form-submit', [AjaxFormController::class, 'submitForm']);

4. Create Blade View with the Form

Create a new Blade view resources/views/ajax-form.blade.php with the form and Ajax code:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Laravel 6 Ajax Form Submit with Custom Validation</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>Ajax Form Submission with Custom Validation</h1> <form id="ajaxForm"> @csrf <label for="name">Name:</label> <input type="text" name="name" id="name" required><br><br> <label for="email">Email:</label> <input type="email" name="email" id="email" required><br><br> <label for="age">Age:</label> <input type="text" name="age" id="age" required><br><br> <button type="submit">Submit</button> </form> <div id="response"></div> <script> $(document).ready(function () { $('#ajaxForm').on('submit', function (e) { e.preventDefault(); // Get form data var formData = new FormData(this); $.ajax({ url: "{{ url('/ajax-form-submit') }}", // Form submission URL type: "POST", data: formData, processData: false, contentType: false, success: function (data) { // On success, display success message if (data.success) { $('#response').html('<p style="color: green;">' + data.success + '</p>'); } }, error: function (xhr) { // On error, display validation errors var errors = xhr.responseJSON.errors; var errorMessages = ''; for (var key in errors) { errorMessages += '<p style="color: red;">' + errors[key] + '</p>'; } $('#response').html(errorMessages); } }); }); }); </script> </body> </html>

5. Explanation of the Code

  • Form: The form contains three fields: Name, Email, and Age.

  • Ajax Script: The form submission is handled via Ajax using jQuery. When the form is submitted, the data is sent via a POST request to the /ajax-form-submit route.

  • Validation: Laravel's Validator is used to validate the data on the server side:

    • Name: Required, minimum 3 characters.

    • Email: Required, must be a valid email.

    • Age: Required, must be an integer and at least 18.

  • Error Handling: If validation fails, the server will return validation errors in JSON format, which will be displayed dynamically in the view.

6. Run Your Application

Start the Laravel development server:

php artisan serve

Now, visit the application in your browser:

http://127.0.0.1:8000/ajax-form

Test the Form

  • Leave some fields empty or input invalid data to trigger validation errors.

  • On successful submission, a success message will appear.

7. Conclusion

With this approach, you’ve:

  • Set up an Ajax form submission in Laravel 6.

  • Validated form inputs on the server side using custom validation.

  • Handled form errors and success responses with Ajax.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

1 Comments

CAN FEEDBACK
  1. Unknown
    Unknown
    Dear Brother, Your article is very helpful. Carry on.
close