S.M_Emamian
S.M_Emamian

Reputation: 17393

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 .

Upvotes: 0

Views: 211

Answers (2)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

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) {...});

Upvotes: 2

Change

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

To

$.post("your route here along with the base url", {username:email,pass:pass}, function (data) {

Example:

$.post("BASE_URL + "admin/checkUserPassLogin")

Where BASE_URL is set somewhere in your view, preferably a base view:

<script type="text/javascript">
    var BASE_URL = '{{ asset('/') }}';
</script>

Upvotes: 0

Related Questions