Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to send the AJAX request to JavaScript?

I want to send the AJAX request to JavaScript, JavaScript, JavaScript.

How do I do it?

script

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.send();

Controller

?

web.php

?

0 likes
3 replies
LaryAI's avatar
Level 58

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.

vincent15000's avatar

Impossible to send a request to JavaScript.

What are you trying to do ?

Why don't you read some documentation about requests ?

1 like

Please or to participate in this conversation.