← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

AJAX Patterns for PHP Backends

javascript ES2017 Intermediate
debt(d5/e3/b3/t7)
d5 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'specialist tool catches it' (d5). The detection_hints list eslint and semgrep as tools, with code_pattern examples like 'fetch() POST without CSRF header' and 'no response.ok check'. These are not default linter rules but require configured rules or semgrep patterns to catch reliably, placing this between default linter (d3) and specialist tool (d5); the tools listed are specialist/configured, so d5 is the best fit.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3). The quick_fix is a small, consistent change: add CSRF token header, check response.ok, and set Accept header. This is more than a one-line patch (multiple call sites may need updating) but is a straightforward pattern replacement rather than a multi-file refactor, matching e3.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3). The applies_to scope is web only, and the concern is limited to JavaScript/PHP integration points (AJAX calls). While every AJAX call in the codebase must follow the pattern, the burden doesn't bleed into unrelated components — it's a persistent but localised convention tax rather than a cross-cutting architectural shape.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'serious trap' (t7). The canonical misconception is that 'PHP can automatically detect AJAX requests' — it cannot; developers must explicitly send and check headers server-side. This directly contradicts how developers familiar with frameworks (e.g. Laravel's Request::ajax() wrapper, which itself requires the header) or other ecosystems might expect automatic detection to work. Additionally, PHP silently returning HTML error pages when JSON is expected is a non-obvious failure mode that contradicts developer expectations, warranting t7.

About DEBT scoring →

Also Known As

AJAX XHR fetch to PHP PHP API calls

TL;DR

Patterns for communicating with PHP backends via fetch — JSON APIs, CSRF tokens, error handling, and response parsing.

Explanation

PHP-specific AJAX concerns: include CSRF token on every state-changing request (POST/PUT/DELETE), handle PHP's error response formats (HTML error pages vs JSON), and set Accept: application/json so PHP can detect AJAX and return JSON not a redirect. PHP side: check if request is AJAX via $_SERVER['HTTP_X_REQUESTED_WITH'] or Accept header. Classic XHR is obsolete — use fetch() with async/await everywhere.

Common Misconception

PHP can automatically detect AJAX requests — PHP has no native AJAX detection; you must send a header like X-Requested-With: XMLHttpRequest or Accept: application/json and check it server-side.

Why It Matters

PHP applications mixing HTML-rendered pages and JSON API endpoints need consistent patterns for authentication, CSRF, error responses, and content negotiation.

Common Mistakes

  • Not including CSRF token on POST requests
  • Not checking response.ok before parsing JSON
  • PHP returning HTML error page when JSON was expected
  • Using XMLHttpRequest instead of fetch

Code Examples

✗ Vulnerable
// No CSRF, no error check, no content negotiation:
fetch('/api/save', {
    method: 'POST',
    body: JSON.stringify(data)
}).then(r => r.json()).then(console.log);
✓ Fixed
async function postToPhp(url, data) {
    const res = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').content,
        },
        body: JSON.stringify(data),
    });
    if (!res.ok) {
        const err = await res.json().catch(() => ({ message: 'Server error' }));
        throw new Error(err.message);
    }
    return res.json();
}

Added 17 Mar 2026
Edited 22 Mar 2026
Views 28
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
1 ping F 3 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 0 pings T 1 ping W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Perplexity 8 Amazonbot 8 Unknown AI 3 Ahrefs 2 Google 2 ChatGPT 1 Majestic 1
crawler 23 crawler_json 1 pre-tracking 1
DEV INTEL Tools & Severity
🟠 High ⚙ Fix effort: Low
⚡ Quick Fix
Always include CSRF token header, check response.ok, and send Accept: application/json so PHP returns JSON not HTML error pages
📦 Applies To
javascript ES2017 web
🔗 Prerequisites
🔍 Detection Hints
fetch() POST without CSRF header; no response.ok check; XMLHttpRequest usage instead of fetch
Auto-detectable: ✓ Yes eslint semgrep
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Medium Context: Function Tests: Update
CWE-352 CWE-79

✓ schema.org compliant