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.

View

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>
       </div>
       <form action="{{url('/enquiry')}}" method="post">
       {{ csrf_field() }}
       <div class="contact-form">
       <div class="alert alert-danger print-error-msg" style="display:none">
           <ul></ul>
       </div>
       <div class="alert alert-success print-success-msg" style="display:none">
       </div>
           <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>
               </div>
               <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>
               </div>
               <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>
               </div>
           </div>
       </div>
       <div class="form-group">
           <label>Subject </label>
           <input type="text" class="form-control" placeholder="Subject" name="subject" value="{{old('subject')}}"/>
       </div>
       <div class="form-group">
           <label>Message </label>
           <textarea rows="4" cols="50" class="form-control" placeholder="Message" name="message">{{old('message')}}</textarea>
      </div>
       <div class="form-group">
           <div class="text-center"><button  type="button" class="btn btn-primary btn-contact">Submit</button></div>
       </div>
   </div>
   </form>
</section>
<!-- /.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>
<script>
//Form post code
$(document).ready(function() {
     // on button click we are getting values by input name.
      $(".btn-contact").click(function(e){
        e.preventDefault();
        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();
        $.ajax({
              url: "<?php echo url('/enquiry');?>",
              type:'POST',
              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.
                  if($.isEmptyObject(data.error)){
                    $(".print-error-msg").find("ul").html('');
                    $(".print-error-msg").css('display','none');
                    $(".print-success-msg").html('');
                    $(".print-success-msg").css('display','block');
                    $(".print-success-msg").html(data.success);
                    $("input[name='name']").val('');
                    $("input[name='contemail']").val('');
                    $("input[name='contmobile']").val('');
                    $("input[name='subject']").val('');
                    $("textarea[name='message']").val('');
                  }else{
                    errorMsg(data.error);
                  }
              }
          });
      }); 
      // Function to show error messages
    function errorMsg (msg) {
      $(".print-success-msg").find("ul").html('');
      $(".print-success-msg").css('display','none');
      $(".print-error-msg").find("ul").html('');
      $(".print-error-msg").css('display','block');
      $.each( msg, function( key, value ) {
        $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
      });
    }
  });
</script>

Controller

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

<?php
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',
        );
        $validator->setAttributeNames($attributeNames);
        //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!']);
     }
}

Routes

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]');

Conclusion

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