I want to change a value based on the selected year and week with ajax.
This is my ajax function:
function changeBekeken() {
var year = $("#jaar-nr").val();
var week = $("#week-nr").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/planning/viewed",
type: "POST",
data: {
year_nr: year,
week_nr: week
},
dataType: "json",
success: function(data) {
alert(data);
}
});
}
$(document).ready(function(){
$("#week-nr").change(function(){
changeBekeken();
});
$("#jaar-nr").change(function(){
changeBekeken();
});
});
This is the route:
Route::post('/planning/viewed', 'PlanningController@viewed');
The data is send to a controller function:
public function viewed(Request $request) {
$check = DB::table('planning_files')
->where([
['user_id', Auth::user()->id],
['created_year', $request->input('year_nr')],
['week', $request->input('week_nr')],
])
->select('seen')
->first();
if($check) {
return json_encode($check, JSON_PRETTY_PRINT);
} else {
return json_encode(false);
}
}
However even when I use $request->all(); request is always empty. My function will always return false. Pretty much this exact same function works on another page, but I can't seem to get this one working.
I have tried adding some extra information to the ajax function, like content type and data type, but none seem to work.
Any tips?
Edit 1
These are the namespaces and classes I use in my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Auth;
use Storage;
Edit 2
When I copy the function to another page it works properly. It has something to do with the content on the page I use the ajax function on. Probably some conflict with the token. I will try to resolve this and post the answer for others if they might have the same problem in the future.