Hi!
I am trying to implement pagination with AJAX, and using plain Javascript to do it. The problem is that when I run request()->ajax(), the header "X-Requested-With" isn't set.
Here's the code:
UserController.php
public function showProfile(string $username) {
if (!Auth::check()) return redirect('/login');
$this->authorize('list', Project::class);
$projects = Auth::user()->userProjects();
if(request()->ajax()) {
$viewHTML = view('partials.user_projects', ['projects' => $projects])->render();
echo $viewHTML;
return response()->json(array('success' => true, 'html' => $viewHTML));
}
$notifications = Auth::user()->userNotifications();
$taskCompletedWeek = Auth::user()->taskCompletedThisWeek()[0];
$taskCompletedMonth = Auth::user()->taskCompletedThisMonth()[0];
$sprintsContributedTo = Auth::user()->sprintsContributedTo()[0];
return view('pages/user_profile', ['projects' => $projects, 'taskCompletedWeek' => $taskCompletedWeek, 'taskCompletedMonth' => $taskCompletedMonth,
'sprintsContributedTo' => $sprintsContributedTo, 'notifications' => $notifications]);
}
I only want the projects view when it is an AJAX Request.
Javascript file
function sendAjaxRequest(method, url, data, handler) {
let request = new XMLHttpRequest();
request.open(method, url, true);
request.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.addEventListener('load', handler);
if(data != null)
request.send(encodeForAjax(data));
else
request.send();
}
function getUserProjectsPage(event) {
event.preventDefault();
var page = event.target.href.split('page=')[1];
sendAjaxRequest('get', event.target.href, null, changePage);
}
function changePage() {
var response = JSON.parse(this.responseText);
console.log(response);
let content = document.querySelector("div.#projects");
content.innerHTML = response.html;
}
I searched a bit, and found out that jQuery adds this header to the request, but I can't use jQuery because this is a college project and we are forbidden to use it. Any suggestions?
Thanks in advance!