To handle the AJAX request in Laravel, you need to define a route in web.php that points to a controller method. In the controller method, you can perform any necessary logic and return a response.
Here's an example:
web.php:
Route::post('/my-url', 'MyController@handleAjaxRequest');
MyController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MyController extends Controller
{
public function handleAjaxRequest(Request $request)
{
// Perform any necessary logic here
$data = ['message' => 'Hello from the server!'];
// Return a JSON response
return response()->json($data);
}
}
In your JavaScript code, you can then make the AJAX request to the URL defined in web.php:
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
const xhr = new XMLHttpRequest();
xhr.open('POST', '/my-url');
xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response.message);
} else {
console.error('Error:', xhr.statusText);
}
};
xhr.onerror = function() {
console.error('Error:', xhr.statusText);
};
xhr.send(JSON.stringify({}));
This code sends a POST request to /my-url with the CSRF token in the header and an empty JSON payload. When the server responds with a 200 status code, the response message is logged to the console. If there's an error, the error message is logged to the console.