Understanding Laravel 5 ajax post

Sometime we need to use alternate way to post or data without page refresh. so why we use ajax post to post our form data on button click. In this article we will use an example of laravel 5 ajax post with validation. We will use jquery ajax to post our form data in simple way. Laravel 5 provide simple way to use validation with ajax post using json response. Here Request class functions of laravel 5.

Laravel 5 ajax post validation example

We will make an example form and post data using jquery ajax and validate our form and return if any error and show the errors back on view. Below is a screen what we are making.


Below is our view file code under resources/views/enquiry.blade.php which will help to create from.

<section class="contactus" id="contactus">
   <div class="container">
       <div class="title-center-heading">
           <h2>Contact us </h2>
       <form action="{{url('/enquiry')}}" method="post">
       {{ csrf_field() }}
       <div class="contact-form">
       <div class="alert alert-danger print-error-msg" style="display:none">
       <div class="alert alert-success print-success-msg" style="display:none">
           <div class="row">
               <div class="col-sm-4 col-md-4 col-lg-4">
                   <div class="form-group">
                       <label>Name </label>
                       <input type="text" class="form-control" placeholder="Name" name="name" value="{{old('name')}}"/>
               <div class="col-sm-4 col-md-4 col-lg-4">
                   <div class="form-group">
                       <label>Email </label>
                       <input type="email" class="form-control" placeholder="Email" name="contemail" value="{{old('contemail')}}"/>
               <div class="col-sm-4 col-md-4 col-lg-4">
                   <div class="form-group">
                       <label>Mobile </label>
                       <input type="text" class="form-control" placeholder="Mobile" name="contmobile" value="{{old('contmobile')}}"/>
       <div class="form-group">
           <label>Subject </label>
           <input type="text" class="form-control" placeholder="Subject" name="subject" value="{{old('subject')}}"/>
       <div class="form-group">
           <label>Message </label>
           <textarea rows="4" cols="50" class="form-control" placeholder="Message" name="message">{{old('message')}}</textarea>
       <div class="form-group">
           <div class="text-center"><button  type="button" class="btn btn-primary btn-contact">Submit</button></div>
<!-- /.End -->

JS to post data

Below are our js code which we are using to post form data in laravel 5 using ajax post. add the js in footer or same view file at the end of view code.

// Jquery library
<script src="{{URL::to('public/assets/plugins/jquery-1-11-3.min.js')}}"></script>
//Form post code
$(document).ready(function() {
     // on button click we are getting values by input name.
        var _token = $("input[name='_token']").val(); // get csrf field.
        var name = $("input[name='name']").val();
        var contemail = $("input[name='contemail']").val();
        var contmobile = $("input[name='contmobile']").val();
        var subject = $("input[name='subject']").val();
        var message = $("textarea[name='message']").val();
              url: "<?php echo url('/enquiry');?>",
              data: {_token:_token, name:name, contemail:contemail, contmobile:contmobile, subject:subject, message:message},
              success: function(data) {
                  // No error empty the field and previous error msg if any.
      // Function to show error messages
    function errorMsg (msg) {
      $.each( msg, function( key, value ) {


Below we are making a controller under app/http/controllers with named EnquiryController.

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Redirect;
class EnquiryController extends Controller

 * Show the application dashboard.
 * @return \Illuminate\Http\Response
    public function index(Request $request)
        // messages for regex validation.
        $messages = [
            'name.regex' => 'This field must contain letters, spaces, dashes. ',
            'subject.regex' => 'This field must contain letters, spaces, dashes. ',
        // Validate fields
        $validator = Validator::make($request->all(), [
            // Using a rgex for validate name.
            'name' => 'required|regex:/^[\pL\s\-]+$/u',
            'contemail' => 'required|email',
            'contmobile' => 'required|numeric',
            'subject' => 'required|regex:/^[\pL\s\-]+$/u',
            'message' => 'required',
        ], $messages);

        $attributeNames = array(
            'contemail' => 'Email',
            'contmobile' => 'Cell Number',
        //Redirect back if validation fails
        if($validator->fails()) {
            return response()->json(['error'=>$validator->errors()->all()]);
        // Else do your stuff here all validation passes.
        // sending an email and redirect back with success message.
        return response()->json(['success'=>'Your enquiry has been successfully submitted!']);


Add your get and post routes in routes/web.php.

// GET Route
Route::get('/enquiry', function () {
    return view('enquiry');
//POST route
Route::post('enquiry', '[email protected]');


So now you can quickly done laravel 5 ajax post with validation. I am included example in simple way to post data using ajax in laravel 5 there can be many ways of js to post. i think i made a simple way to get things done. Leave comment below if you have any issue.

Cheers! happy coding!

Adam Brown
Please follow and like us:

Leave a Comment