Laravel 11 Form Submit Using Ajax Example

Laravel 11 Form Submit Using Ajax Example

Form submit using Ajax in Laravel 11; First, create a form and apply jQuery and Ajax code with this form to validate the form before submitting after that create two routes and methods, that will handle the form submission in applications.

Laravel 11 was released on March 12, 2024, and we are building an application to submit a form using Ajax and also validate the form data using jQuery without refreshing the page in laravel 11.

Laravel 11 Ajax Form Submit Validation Example

Steps to validate form before submitting using jQuery AJAX in Laravel 11 without refreshing the page:

Step 1 – Define Ajax Form Routes

Routes need to be defined to display AJAX form and send form data to the controller using AJAX, simply navigate to routes folder and open web.php, then create routes for the form like following in web.php file:

use App\Http\Controllers\AjaxFormController;

Route::get('form', [AjaxFormController::class, 'index']);
Route::post('save', [AjaxFormController::class, 'store']);

Step 2 – Create Form on View

To create form on view file; Just navigate to the resources/views folder and create an ajax-form.blade.php file inside it, and then create the form in it like the following:

<!DOCTYPE html>
<html>
<head>
    <title>Submit Form using Ajax with Validation in Laravel 11 - Tutsmake.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <style>
    .error{
     color: #FF0000; 
    }
  </style>

</head>
<body>

<div class="container mt-4">

  <div class="card">
    <div class="card-header text-center font-weight-bold">
      <h2 class="text-center">Submit Form using Ajax with Validation in Laravel 11 - Tutsmake.com</h2>
    </div>
    <div class="card-body">
      <form name="formAjax" id="formAjax" method="post" action="javascript:void(0)">
       @csrf

        <div class="form-group">
          <label for="exampleInputEmail1">Name</label>
          <input type="text" id="name" name="name" class="form-control">
        </div>          

         <div class="form-group">
          <label for="exampleInputEmail1">Email</label>
          <input type="email" id="email" name="email" class="form-control">
        </div>           

        <div class="form-group">
          <label for="exampleInputEmail1">Message</label>
          <textarea name="message" id="message" class="form-control"></textarea>
        </div>

        <button type="submit" class="btn btn-primary" id="submit">Submit</button>
      </form>
    </div>
  </div>
</div>  

</body>
</html>

Step 3 – Implement Ajax Form Submit

To send data from the form to the controller and validate it, you need to write jQuery AJAX code and add it to the form blade view file, which you can write something like this:

<script>
if ($("#formAjax").length > 0) {
$("#formAjax").validate({
  rules: {
    name: {
    required: true,
    maxlength: 50
  },
  email: {
    required: true,
    maxlength: 50,
    email: true,
  },  
  message: {
    required: true,
    maxlength: 300
  },   
  },
  messages: {
  name: {
    required: "Please enter name",
    maxlength: "Your name maxlength should be 50 characters long."
  },
  email: {
    required: "Please enter valid email",
    email: "Please enter valid email",
    maxlength: "The email name should less than or equal to 50 characters",
  },   
  message: {
    required: "Please enter message",
    maxlength: "Your message name maxlength should be 300 characters long."
  },
  },
  submitHandler: function(form) {
  $.ajaxSetup({
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

  $('#submit').html('Please Wait...');
  $("#submit"). attr("disabled", true);

  $.ajax({
    url: "{{url('save')}}",
    type: "POST",
    data: $('#formAjax').serialize(),
    success: function( response ) {
      $('#submit').html('Submit');
      $("#submit"). attr("disabled", false);
      alert(response.message);
      document.getElementById("formAjax").reset(); 
    },
    error: function( response ) {
      $('#submit').html('Submit');
      $("#submit"). attr("disabled", false);
      console.log(response.responseJSON.message);
      alert(response.responseJSON.message);
      document.getElementById("formAjax").reset(); 
    }
   });
  }
  })
}
</script>

Important Note:- If you forgot to add csrf_token with your Laravel Ajax form, then you got the error CSRF token mismatch and 419 status code. We have added csrf_token as an example, you can see it in the form.blade.php view file with ajax script code.

Step 4 – Create Controller and Method

To create a controller file, which is used to show the form and store the form data in the MySQL database; Run the following command cmd or terminal to create a new controller file:

php artisan make:controller AjaxFormController

Now, navigate open AjaxFormController.php file from app/http/controllers folder and create two methods into it, which are used to show the form and accept form data via ajax request to validate on server side, and return a message in json response, which you can do something like this:

    public function index()
    {
        return view('ajax-form');
    }

    public function store(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'name' => 'required',
                'email' => 'required|email',
                'message' => 'required'
            ]);

            // Process the validated data
            return response()->json(['message' => 'Added new record.']);
        } catch (\Illuminate\Validation\ValidationException $e) {
            // If validation fails, return the validation error message
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

Step 5 – Run and Test Application

To run and test laravel application; run the php artisan serve command on cmd or terminal window:

php artisan serve

Now open your browser and type the following URL:

http://127.0.0.1:8000/form

Conclusion

In this handy guide, you saw how to create a form and send data from that form to the controller using Ajax and also validate it using jQuery without submitting it in laravel 11 applications.

If you have any query regarding sending Laravel form data to controller using ajax jQuery, then don’t worry you can ask in comment box or mail to [email protected].

Recommended Guides

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *