I am doing a PATCH request. The request goes through and returns as it should but it is not ajax.
I added an if statement to check this. How is it possible to use Axios and it is not ajax? I thought that Axios is a library that wraps around ajax.
Any tips?
(Tried with GET or POST, same result. Not Ajax)
in HTML
<button data-id="1">button</button>
in Javascript file
let button = document.querySelector('button');
button.addEventListener('click', event => {
let id = button.getAttribute('data-id');
patchRequest(id);
});
const patchRequest = async (id) => {
try {
const response = await axios.patch(`/action/${id}`);
return response.data.success;
} catch (err) {
return console.log(err.response.data);
}
};
inside the Controller
public function __invoke(Request $request)
{
// do something and then respond
if($request->ajax()) {
return response()->json(['success' => $result], 201);
} else {
return 'not ajax';
}
}
in web.php (Routes file)
Route::patch('action/{id}', SomeController::class);
UPDATE
User @TJCrowder helped with his comment.
What solved my problem was adding this
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
My suspicion is that the ajax
method is looking for the header often used on ajax requests, HTTP_X_REQUESTED_WITH
. axios
probably doesn't set that header, but you can do it manually if you like.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.