lundi 18 mai 2020

Ajax POST request in Laravel 5.2 for Local storage variables

I am trying to send 2 variables from my local storage from a blade view that had no input but an attached JS file that generated those two variables and send it with ajax to a controller which will add the information to the database.

In my blade I added the meta information for the token: <meta name="csrf_token" content="" />

My ajax request looks like this:

$.ajax({
            type: 'POST',
            url: '/addvote',
            headers:
                {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
            dataType: "json",
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                id: localStorage.getItem('id'),
                number: localStorage.getItem('number')
            },
        });

I have added a POST route: Route::post('/addvote', "CandidateController@addvote");

And my function in controller looks like this:

public function addvote(Request $request){
        $id_candidate = $request['id'];
        ...
        return redirect("/home");

    }

Can someone explain me if I have to have this CSRF token if I am sending data that wasn't collect in the blade and if so, what am I missing or doing wrong because I get server error 500.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire