S.M_Emamian S.M_Emamian - 4 months ago 12
PHP Question

how to post to a route url in laravel

I'm using this route :

Route::post('cp/admin/checkUserPassLogin','Panel\AdminController@checkUserPassLogin');


and my controller :

enter image description here

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use DB;
use App\Quotation;
....
public function checkUserPassLogin(Request $request)
{
echo 'test';
return 'test';

}


and in the my view:

function login()
{
console.log('test');
var email = $('#email_admin').val();
var pass = $('#pass_admin').val();

if(!email || !pass)
return ;

console.log(email+'-'+pass);
$.post("{{ url('/cp/admin/checkUserPassLogin') }}", {username:email,pass:pass}, function (data) {


console.log(data);


if(data == 'ok')
{
window.location.href = "..........";
}else{

}

});
}


console.log(email+'-'+pass);
prints my values but
console.log(data);
doesn't return anything .

Answer

Undoubtedly, is a CSRF problem. In Laravel 5, all requests must pass through the Middleware which will not allow any POST requests without the correct CSRF token. To solve this problem:

Somewhere in your view add:

<meta name="csrf-token" content="{!! csrf_token() !!}">

Then in your ajax post data add :

'_token': $('meta[name="csrf-token"]').attr('content')

It will look like this:

$.post("{{ url('/cp/admin/checkUserPassLogin') }}", {username:email, pass:pass, '_token': $('meta[name="csrf-token"]').attr('content')}, function (data) {...});

One alternative, is to add the csrf-token directly to your javascript like you did with the URL:

$.post("{{ url('/cp/admin/checkUserPassLogin') }}", {username:email, pass:pass, '_token': "{!! csrf_token() !!}"}, function (data) {...});
Comments