Laravel 9 Form Submit Using jQuery Ajax Using Controller

In this tutorial, we will learn how to submit a form using jQuery Ajax in Laravel 9. Ajax allows us to submit form data without refreshing the page, providing a better user experience.

Sure, here’s a summary of each step:

Step 1: Set up Laravel 9

  • Create a new Laravel 9 project using Composer.

Step 2: Create a Form

  • Create a new view file called form.blade.php.
  • Add a form with two input fields (name and email) and a submit button.
  • Add an output element to display the result of the form submission.

Step 3: Set up the Route

  • Add a new route to routes/web.php that will handle the form submission.

Step 4: Create the Controller

  • Create a new controller using php artisan make:controller FormController.
  • Add a submitForm method to the controller that will handle the form data.

Step 5: Submit the Form Using Ajax

  • Add a script to your form.blade.php file that binds the submit event to the form and prevents the default form submission behavior.
  • Send an Ajax POST request to the submit-form route with the serialized form data.
  • Display a success message in the output element if the form submission was successful; otherwise, display an error message.

Here are the details.

Step 1: Set up Laravel 9

Before we get started, we need to set up a new Laravel 9 project. You can do this by running the following command in your terminal:

composer create-project --prefer-dist laravel/laravel example-app

Step 2: Create a Form

Next, we will create a simple form that we will submit using Ajax. In your Laravel project, create a new view file called form.blade.php in the resources/views directory. Here’s an example form:

<form id="myForm">
    @csrf
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" name="name">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" id="email" name="email">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<p>Result:</p>
<output id="result"></output>

This form has two fields (name and email) and a submit button. Note the @csrf directive, which adds a CSRF token to the form for security reasons. Additionally, we added an output element to display the result of the form submission.

Step 3: Set up the Route

Next, we need to create a route that will handle the form submission. In your routes/web.php file, add the following code:

Route::post('/submit-form', [FormController::class, 'submitForm'])->name('submit-form');

This route will call the submitForm method in the FormController when the form is submitted.

Step 4: Create the Controller

Now, we need to create the FormController that will handle the form submission. In your terminal, run the following command to create a new controller:Copy

php artisan make:controller FormController

Then, open the app/Http/Controllers/FormController.php file and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function submitForm(Request $request)
    {
        $name = $request->input('name');
        $email = $request->input('email');

        // Do something with the form data (e.g. save to database)

        return response()->json(['success' => true]);
    }
}

This method will be called when the form is submitted. We retrieve the name and email input values from the request and do something with the data (e.g. save it to a database). Then, we return a JSON response indicating that the form was submitted successfully.

Step 5: Submit the Form Using Ajax

Finally, we need to submit the form using Ajax. In your form.blade.php file, add the following code at the bottom of the file:

<script>
    $(document).ready(function() {
        $('#myForm').submit(function(e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "{{ route('submit-form') }}",
                data: $(this).serialize(),
                success: function(response) {
                    $('#result').html('Form submitted successfully!');
                },
                error: function(response) {
                    $('#result').html('An error occurred while submitting the form.');
                }
            });
        });
    });
</script>

This code binds the submit event to the form and prevents the default form submission behavior. Then, it sends an Ajax POST request to the submit-form route with the serialized form data. When the request is successful, it displays a success message in the output element. If an error occurs, it displays an error message instead.

Conclusion

In this tutorial, we learned how to submit a form using jQuery Ajax in Laravel 9. Ajax allows us to submit form data without refreshing the page, providing a better user experience. We created a simple form with two input fields and a submit button, set up a route to handle the form submission, created a controller to handle the form data, and submitted the form using Ajax.