PHP

How to Use AJAX with Laravel (Easy Examples)

Updated

laravel ajax

An Ajax POST to a Laravel route in the web middleware group fails with HTTP 419 “Page Expired” when the request carries no valid CSRF token. Send the token as an X-CSRF-TOKEN header (read it from <meta name="csrf-token" content="{{ csrf_token() }}">) or as a _token field in the body, and the same request returns 200. Here is the failure and the fix, both measured against a stock install:

$ curl -s -i -X POST http://127.0.0.1:8899/submit-form -d "name=Ada"
HTTP/1.1 419 unknown status
...
     419 | Page Expired

$ curl -s -i -b cookies.txt -X POST http://127.0.0.1:8899/submit-form \
    -H "X-CSRF-TOKEN: KuPBQFVyDyMxVQfFzVQDKaNXcFWYoeQSlp3VaPnc" -d "name=Ada"
HTTP/1.1 200 OK
{"message":"Hello, Ada!"}

The reason phrase really is unknown status: 419 is not an IANA-registered code, so curl has no name for it. Laravel’s own error page titles it “Page Expired”.

Authorize and validate Ajax routes

In an Ajax CRUD example whose routes have no authentication and no authorization, Route::put('/projects/{id}', ...) and Route::delete('/projects/{id}', ...) are open to anyone. That is not a stylistic quibble. Run as written, an anonymous request destroys another user’s row:

$ curl -s -X DELETE -H "Sec-Fetch-Site: same-origin" http://127.0.0.1:8899/projects/1
{"message":"Project deleted"}
-- rows left: id=2 name=Hijack

CSRF protection does not help here, because CSRF only stops a victim’s browser from being tricked into making the request. It does nothing about an attacker making the request directly with curl, where every header is theirs to choose. Authorization is a separate control:

Route::middleware('auth')->put('/api/projects/{project}', function (Request $request, Project $project) {
    abort_unless($request->user()->can('update', $project), 403);

    $validated = $request->validate([
        'name' => ['required', 'string', 'max:255'],
        'description' => ['nullable', 'string', 'max:500'],
    ]);

    $project->update($validated);   // the validated array, never $request->all()

    return response()->json($project);
});

Each control was measured separately. The auth middleware turns an anonymous request away:

$ curl -s -o /dev/null -w "%{http_code}\n" -X PUT -H "Accept: application/json" \
    http://127.0.0.1:8899/api/secure-projects/2 -d "name=x"
401

and validate() rejects a bad payload before anything is written:

$ curl -s -i -X POST -H "Accept: application/json" http://127.0.0.1:8899/api/projects -d "description=no+name"
HTTP/1.1 422 Unprocessable Content
{"message":"The name field is required.","errors":{"name":["The name field is required."]}}

$ curl -s -i -X POST -H "Accept: application/json" http://127.0.0.1:8899/api/projects -d "name=Valid&description=ok"
HTTP/1.1 201 Created

Project::find($id) without a null check returns {} with a 200 on a missing id, and on the update route it produced a real 500 — Call to a member function update() on null. Route model binding returns a clean 404 instead (measured: GET /bound/999 -> 404). And while $request->all() is a bad habit, it was not exploitable as written: with $fillable = ['name', 'description'], forcing user_id=99 through it was silently dropped and the row kept user_id=1. It becomes exploitable the moment someone widens $fillable.

Laravel 13 no longer requires a token for same-origin requests

This is the behaviour change most likely to confuse anyone debugging a 419 today. In Laravel 13 the CSRF middleware accepts a request outright if the browser sent Sec-Fetch-Site: same-origin, token or no token. Measured on 13.24.0, identical POSTs to the same tokenless route:

Sec-Fetch-Site: same-origin  -> 200
Sec-Fetch-Site: same-site    -> 419
Sec-Fetch-Site: cross-site   -> 419
Sec-Fetch-Site: none         -> 419
(header absent)              -> 419

Browsers set that header themselves and page JavaScript cannot forge it, so cross-origin forgery is still blocked. The practical consequence: a fetch() from your own page may work with no token at all, while the curl command you reach for to reproduce the bug returns 419 — because curl sends no Sec-Fetch-Site at all. Keep sending the token; it is the branch that works for every client.

The middleware itself has been renamed. There is no app/Http/Middleware/VerifyCsrfToken.php in the skeleton any more, and the class in the web group is now Illuminate\Foundation\Http\Middleware\PreventRequestForgery; ValidateCsrfToken survives only as a deprecated alias:

// vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidateCsrfToken.php
/**
 * @deprecated Use PreventRequestForgery instead.
 */
class ValidateCsrfToken extends PreventRequestForgery

// PreventRequestForgery::handle() — the branch that fails
throw new TokenMismatchException('CSRF token mismatch.');

// Illuminate/Foundation/Exceptions/Handler.php:768 — where 419 comes from
$e instanceof TokenMismatchException => new HttpException(419, $e->getMessage(), $e),

To exclude a route (a webhook, say), configure it in bootstrap/app.php rather than editing a middleware class that no longer exists. The fluent method was renamed to match; validateCsrfTokens() still works but is marked @deprecated Use preventRequestForgery() instead:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: ['stripe/*']);
})
POST /stripe/webhook (no token, no Sec-Fetch-Site) -> 200
POST /submit-form    (still protected)             -> 419

The three places Laravel will look for the token

PreventRequestForgery::getTokenFromRequest() reads exactly these, in order:

$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
    $token = CookieValuePrefix::remove($this->encrypter->decrypt($header, static::serialized()));
}

All three were confirmed to return 200 on the same route. @csrf in a Blade form renders the first one — the real output is <input type="hidden" name="_token" value="dqM4OD9oP4ebS5RlR5tAc5e71BerwSpddWSOCiZh" autocomplete="off">. The third is the encrypted XSRF-TOKEN cookie, which Laravel still sets on every response that passes the middleware:

Set-Cookie: XSRF-TOKEN=eyJpdiI6IjdCREdyTHlPM0ZvbkwzT3dXR1JHSGc9PSIsInZhbHVlIjoi...; path=/; samesite=lax

Drop the jQuery — the skeleton has none, and neither does axios

A stock Laravel 13.24.0 install ships neither jQuery nor axios: package.json lists only vite, tailwindcss, @tailwindcss/vite, laravel-vite-plugin and concurrently, and resources/js/app.js is a single //. There is no resources/js/bootstrap.js at all — the file that used to configure axios in older releases is gone. Pulling in a 30 KB library to send one request is not a trade worth making. (If what you actually need is the reverse trip — server-rendered values reaching the script — the safe way to embed PHP data in JavaScript is json_encode with the HTML flags, not string interpolation.)

const token = document.querySelector('meta[name="csrf-token"]').content;

const res = await fetch('/submit-form', {
    method: 'POST',
    headers: {
        'X-CSRF-TOKEN': token,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    body: JSON.stringify({ name: document.getElementById('name').value }),
});

const data = await res.json();   // {"message":"Hello, Ada!"}

Add <meta name="csrf-token" content="{{ csrf_token() }}"> to your layout yourself — the stock welcome.blade.php does not include one. If you do install axios, it reads the XSRF-TOKEN cookie and sets X-XSRF-TOKEN for you, which is why axios examples often appear to need no configuration.

What was not tested here: headless Chromium would not run on this machine, so the fetch() snippet above was not executed in a browser. Its server side was verified with curl against every code path shown, and the Sec-Fetch-Site values browsers send are defined by the W3C Fetch Metadata Request Headers spec rather than measured here. Against a throwaway Laravel app that /verify/ajax-with-laravel.sh builds and serves on a free local port, a tokenless POST returns 419, the X-CSRF-TOKEN and _token forms return 200, and each Sec-Fetch-Site value gets the status listed above.

The 419 is not always the real problem

One more trap specific to Ajax on web routes. The Laravel 13 skeleton ships this in bootstrap/app.php:

$exceptions->shouldRenderJsonWhen(
    fn (Request $request) => $request->is('api/*'),
);

So an exception on /projects renders HTML even when your Ajax call sends Accept: application/json. An unauthenticated request to a route behind auth tried to redirect to a named login route, which the bare skeleton does not define, and the client got a 500 with Route [login] not defined instead of the 401 it expected. The identical route under an /api/ prefix returned 401. Either prefix your Ajax endpoints with api/, widen that closure, or define the login route — otherwise you will spend an afternoon debugging the wrong status code.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.