简体   繁体   中英

401 Unauthorized error on ajax call laravel 5.2

when i am doing ajax call i am getting error as 401 Unauthorized.

this is my ajax code:

var email=document.getElementById( "email" ).value;
  if(email)
  {
      var data = 'email='+ email;
      $.ajax({
              type: 'POST',
              dataType: "json",
              data: {"_token": "{{ csrf_token() }}","data":data},
              url: "{{ URL::to('admin/check_email_exit') }}",
              success: function (response) {
              if(response=="1")
              {
                  $( '#email_status' ).html('Email Already Exists');
                  return false;
              }
              else
              {
                  $( '#email_status' ).html("");
                  return false;
              }
       }
       });
  }
    else
    {
         $( '#email_status' ).html("");
         return false;
    }

my route:

Route::post('admin/check_email_exit', 'CompanyController@check_email_exit');

this is my controller code that checks email exits or not:

public function check_email_exit(){
        $email = $_POST["email"];
        $user_email = DB::table('users')->where('email',$email)->select('*')->get();
        $use_email=count($user_email);
        if($use_email > 0 )
        {
            return "1";
        }
        else
        {
            return "0";
        }
    }

how to resolve this error..??

Just set X-CSRF-Token in ajax Request header

headers: {
  'X-CSRF-Token': {{ csrf_token() }}
}

This may help you.

Check if you need the route that you are calling, the user must be authorized or not. If the case is not, than you can try to define the route outside of auth middleware. Something like this.

Before:

Route::group(['middleware' => 'auth'], function() {
    Route::get('route_name', [Controller::class, 'methd']);
    ... other routes
});

After:

Route::get('route_name', [Controller::class, 'methd']);

Route::group(['middleware' => 'auth'], function() {
    ... other routes
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM