Search code examples
ajaxlaravelcsrf-protection

Laravel 5 X-CSRF-TOKEN 500 (Internal Server Error) in Ajax


Hello I have change password using Ajax (this is a short version of the code):

var password = document.querySelector('[name="password"]').value;

    action = 'http://localhost:8012/market2/market2/public/account/query/';

    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
    } else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
    }

    xmlhttp.open("post",action + password, true);
    xmlhttp.setRequestHeader("X-CSRF-TOKEN", document.getElementById('token-csrf').value);

    xmlhttp.onreadystatechange=function() {
      if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "false") {
            document.getElementById("error_password").innerHTML = "You actually password is wrong!";
            return false;
        } else {
            document.getElementById("error_password").innerHTML = "OK";
            return true;
        }

      }
    }


    xmlhttp.send();

}

And my csrf-token: <input type="hidden" name="_token" id="token-csrf" value="{{ csrf_token() }}">

I don't know did I correct add parameter X-CSRF-TOKEN to my script. First I have error ajax 419 (unknown status) so I added X-CSRF-TOKEN and now I have error 500 (Internal Server Error). I also tried this: Laravel 5.5 ajax call 419 (unknown status)

Edit Post:

Is't my query method:

public function queryPass($pass) {

  $user = Auth::user();
  $current_password = $user->password;

  if(Hash::check($pass, $current_password)) {

    $updatePassword = App\User::where('id', $user->id)->update(['password' => bcrypt($pass)]);
    echo "true";

  } else {

    echo "false";
    die;

  }

}

And route:

Route::get('account/query/{pass?}', 'UsersController@queryPass');

Solution

  • First problem was that he missed use Illuminate\Support\Facades\Hash; at the top of his controller, he used use Hash;, second thing when we resolved that was that, he was returning a boolean from inside a controller, when he is supposed to return an object which implements __toString method or a string, so he returned a correct response in this case a string "true" and "false"