Post data using ajax in laravel 5

Rakesh Sharma      24 Comments  

Post data using ajax in laravel 5 to controller

If you are going to work with ajax data post to controller or route in laravel 5. There are some need to get ajax call work correctly. Your requirement is csrf token. A default feature in Laravel is it’s automatic CSRF security. When you working with forms it’s automatically add a “_token” hidden field to your form. On each post request token will be matched for csrf protection. so it’s one more cool feature provided by laravel 5.

Why on ajax post 500 internal server error laravel :-

If you are using default way for ajax data post, you will get “500 internal server error” in laravel 5. cause you missing csrf token posting with ajax post data. and error reason is token not being matched on post request. so every time a form data is posting require csrf token match. else you will get “500 internal server error” in laravel.

Post data using ajax in laravel 5

In this article we will explore how to solve 500 internal server error in ajax post or call in laravel or how to Post data using ajax in laravel 5. there are many ways to do this but i am sharing two ways :-

1. Adding on each request
2. globally

How to Post data using ajax in laravel 5 :-

1. Adding on each request and post data to controller :-

In this way we need to add token on each ajax call with data which is posting

view :- add a “login.blade.php” under “resources/views/” and add below code to make a form

<div class="secure">Secure Login form</div>
{!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
<div class="control-group">
  <div class="controls">
     {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
<div class="control-group">
  <div class="controls">
  {!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
{!! Form::button('Login', array('class'=>'send-btn')) !!}
{!! Form::close() !!}

Now add your ajax call or post data script to your layout footer or in the same file.

<script type="text/javascript">
      url: 'login',
      type: "post",
      data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val()},
      success: function(data){

Routes :- Add your get and post route to “app/Http/routes.php”

Route::get('account/login', function() {
  return View::make('login');
Route::post('account/login', 'AccountController@login');

Controller :- add a controller to “app/Http/Controllers” with named “AccountController.php” and add below code

<?php namespace App\Http\Controllers;
use Input;
use Request;
class AccountController extends Controller {
  public function login() {
    // Getting all post data
    if(Request::ajax()) {
      $data = Input::all();

After all make go to your page url and click on button and you get your data has been posted and you will get alert with success.

2. globally way :-

In this way we will add token for globally work with ajax call or post. so no need to send it with data post.

1. Add a meta tag to your layout header :- csrf_token() will be the same as "_token" CSRF token that Laravel automatically adds in the hidden input on every form.

<meta name="_token" content="{!! csrf_token() !!}"/>

2. Now add below code to footer of your layout, or where it will set for globally or whole site pages. this will pass token to each ajax request.

<script type="text/javascript">
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }

Now make an ajax post request an you are done your data will post successfully.

  • Pavlo Gagin

    Thanks for that tutorial, but doesn’t work for me unless I added this in my Controller method:

    if (Session::token() !== Input::get(‘_token’)) {
    // your action

    • rakesh sharma

      yeah if you want to check with session token, if you have any error on production check your console for any error. may be some route or post url issue.

  • Nazim Mahmud Khan

    it did work for me in my first attempt……thanks a lot

    • rakesh sharma

      Glad to know it’s helpful for you. Thanks

  • ssalama

    Thanks , but shouldn’t we use data:$(‘#from_id’).serializeArray() instead of building the json object ourselves?

    • rakesh sharma

      Yeah you can use, just use a hidden field for token in form and then try to use serialize().

  • nimmy

    in this code .why don,t work elseif to correct it?

    public function search()

    if($data) {

    if(($data[‘religion’]) and ($data[‘education’])) {
    $query = DB::table(‘user_profile’)
    ->join(‘user_reg’, ‘’, ‘=’, ‘user_profile.user_id’)
    ->where(‘religion’, $data[‘religion’])
    ->where(‘education’, $data[‘education’])->get();
    $query = DB::table(‘user_profile’)
    ->join(‘user_reg’, ‘’, ‘=’, ‘user_profile.user_id’)
    ->whereIn(‘religion’, $data[‘religion’])->get();
    elseif($data[‘education’]) {
    $query = DB::table(‘user_profile’)
    ->join(‘user_reg’, ‘’, ‘=’, ‘user_profile.user_id’)
    ->whereIn(‘education’, $data[‘education’])->get();
    else {
    $query = DB::table(‘user_profile’)
    ->join(‘user_reg’, ‘’, ‘=’, ‘user_profile.user_id’)->get();
    return view(‘search’,array(‘data’=>$query));
    //return view(‘search’);

  • nimmy

    how to get image in controller.this code is not working.

  • Chris Nuvoli

    I tried this one, the data is alerted however then when I call the method in the controller nothing get’s printed. Also, how can you tell the controller to update the view with the new data instead of rendering the view again?

    • rakesh sharma

      To check response you should check your browser console. When you are working with ajax

      • Chris Nuvoli

        1) if you don’t use click(function(e) { e.preventDefault(); the browser will submit normally. 2) the data array is generated but the controller doesn’t receive it with this code (if.ajax … nothing is passed to the controller, the ajax call is not getting to the controller.

  • Classical

    Thanks for this tut. It’s very useful!

  • and now i get another error Failed to load resource: the server responded with a status of 405 (Method Not Allowed) , could you fix that?

    • rakesh sharma

      Just check your browser console and routes?

  • Divo

    Thanks. I missed the routes in my project.

  • Abbas Haroon

    While implementing ajax form data submission, I encountered a 500 internal Server Error. After digging, I found that I was submitting Ajax data without CSRF token and it occured again and again while I was coding the project. Here is this reason explained along with other causes of Laravel Ajax error

  • nikesh shrestha

    i am sending a _token field with a post request but i am still having an issue.
    the data is correctly posted to the server side.
    if is simply echo out or print_r the post data i get the posted data in alert or console in front end but if i try to incorporate any sort of logic in the posted data at the server side i still keep getting status 500.

    note: i am trying to update the database table using the data posted by the ajax request. so i do have
    use DB; at the top.
    is there anything that i am missing???

  • Thx :)

  • Mark Anthony Villudo


  • nipunasudha

    awesome bro! global one worked as a charm! couldnt get to work the first one though :(

  • John William

    Great & Helpful Tutorial. So easy to understand and use Thanks for sharing with us.
    I have also created another Ajax Login Form Using jQuery and PHP

  • Tim

    have an ajax code following your explanation but nothing happens here so how do I need to implement this tried a lot but nothing happens help

  • Lifesound

    Great article

  • Mohammed Hammed

    making ur csrf token global as such surely isnt a decent practice or am i wrong..