Submit Laravel Form Using Ajax Post Method with Validation

In this post, we learn how to submit a form by the Ajax post method in laravel. Ajax is great to submit forms or get data from the database without reloading or refresh the page.

We also validation our data in the Laravel controller and show an error message in your blade file.

Space Ship - 3
Space Ship - 3
Ajax form submit in Laravel

Step 1: Make Route for Submit Form

Here I make two routes one to get the form and another to submit the form.

Route::get('get-form', '[email protected]');
Route::post('submit-form', '[email protected]');

Step 2: Create a Model, Controller and Migration

We create a model, controller, and migration file with the following one command.

php artisan make:model Contact -mcr

By running this command artisan will generate model, controller, and migration file for contact.

Step : 3 Migration Contact Form

To migrate the contact migration run this command

php artisan migrate

Step: 4 Make a Simple Contact Form

In this form, we added a success alert, which is shown when the form is submitted successfully, and an error message, which is come from the Laravel controller.

<div class="alert alert-success" role="alert" id="successMsg" style="display: none" >
  Thank you for getting in touch! 
</div>

  <form id="SubmitForm">
      <div class="mb-3">
        <label for="InputName" class="form-label">Name</label>
        <input type="text" class="form-control" id="InputName">
        <span class="text-danger" id="nameErrorMsg"></span>
      </div>

      <div class="mb-3">
        <label for="InputEmail" class="form-label">Email address</label>
        <input type="email" class="form-control" id="InputEmail">
        <span class="text-danger" id="emailErrorMsg"></span>
      </div>

      <div class="mb-3">
        <label for="InputMobile" class="form-label">Mobile</label>
        <input type="number" class="form-control" id="InputMobile">
        <span class="text-danger" id="mobileErrorMsg"></span> 
      </div>

      <div class="mb-3">
        <label for="InputMessage" class="form-label">Message</label>
        <textarea class="form-control" id="InputMessage" cols="30" rows="4"></textarea>
        <span class="text-danger" id="messageErrorMsg"></span>
      </div>
      
      
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>

Step 5: Jquery Ajax code for sending form

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

<script type="text/javascript">

$('#SubmitForm').on('submit',function(e){
    e.preventDefault();

    let name = $('#InputName').val();
    let email = $('#InputEmail').val();
    let mobile = $('#InputMobile').val();
    let message = $('#InputMessage').val();
    
    $.ajax({
      url: "/submit-form",
      type:"POST",
      data:{
        "_token": "{{ csrf_token() }}",
        name:name,
        email:email,
        mobile:mobile,
        message:message,
      },
      success:function(response){
        $('#successMsg').show();
        console.log(response);
      },
      error: function(response) {
        $('#nameErrorMsg').text(response.responseJSON.errors.name);
        $('#emailErrorMsg').text(response.responseJSON.errors.email);
        $('#mobileErrorMsg').text(response.responseJSON.errors.mobile);
        $('#messageErrorMsg').text(response.responseJSON.errors.message);
      },
      });
    });
  </script>

Step 6: FormController.php

In this file, we validate and store the data method.

 public function store(Request $request)
    {
        $request->validate([
            'name'          => 'required',
            'email'         => 'required|email',
            'mobile'        => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'message'       => 'required',
        ]);


        $contact = new Contact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->mobile = $request->mobile;
        $contact->message = $request->message;
        $contact->save();

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

I hope it can help you…