Reputation: 119
url = '{{route("ajaxSendmsg")}}';
console.log(url);
$.ajax({
url: url,
data : {comment_id:comment_id},
type: "POST",
dataType: "json",
success : function(response){
alert(response);
},
error : function(res){
console.log(res);
}
});
Route:
Route::post('/ajaxSend', ['as'=> 'ajaxSendmsg', 'uses'=>'PostsController@ajaxSend']);
Controller:
public function ajaxSend(){
if( Request::ajax() ){
return Response::json(['success' => 1]);
}
}
Error: TokenMismatchException in VerifyCsrfToken.php line 53:
I'm trying to send ajax request, but it doesn't work. :/
Upvotes: 1
Views: 8907
Reputation:
for use ajax request and response in laravel5. you should send token like this. ::::::::
ajax file::
<input type="hidden" value="{{ csrf_token() }}" id="_token" name="_token" />
$.ajax({
type: 'POST',
url:'{{url("set-visitor")}}' ,
data: {id: '2', _token: $('#_token').val()},
dataType: 'html',
success: function(data){
var rep = JSON.parse(data);
console.log(data);
if(rep.code == 200)
{
console.log(rep);
}
else{
console.log('error');
}
}
});
and Controller file::
public function set_visitor()
{
$id = request('id');
$_token = request('_token');
return Response::json($_token);
}
good luck:♥♥:
Upvotes: 0
Reputation: 15220
Laravel by default has a middleware on non-reading HTTP requests (like POST, PUT or PATCH) to protect against Cross Site Request Forgery. On every response, a token is generated, and then the subsequent request is expected to send along that token. If the tokens match, everything is fine, if not (or if the requests provides no token at all), this might be a CSRF exploit.
There are several ways to go about this:
app/Http/Kernel.php
- obviously not the best idea.``
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Support\Str;
class VerifyCsrfToken extends BaseVerifier
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Str::startsWith($request->getRequestUri(), 'some/open/route') {
return $next($request);
}
return parent::handle($request, $next);
}
}
_token
, in the request string as _token
or as an HTTP header named X-CSRF-TOKEN
. You can get it with the helper function csrf_token()
:``
.ajax({
url: url,
data : {comment_id:comment_id, "_token":"{{ csrf_token() }}"},
type: "POST",
dataType: "json",
....
});
Upvotes: 5