Prevent XSS in AJAX Responses
Cross-site scripting (XSS) occurs when untrusted data is interpreted as executable markup or script. AJAX does not make data safe: a JSON response can still contain attacker-controlled strings.
Prefer text rendering
const item = document.createElement('li');
item.textContent = result.title;
list.append(item);
Avoid assigning untrusted values to innerHTML or jQuery .html(). If rich HTML is genuinely required, use a maintained HTML sanitizer with a carefully defined allowlist.
Escape in the correct context
HTML text, attributes, URLs, JavaScript, and CSS have different encoding requirements. Prefer DOM APIs that treat values as text. On the server, validate input and encode output at the point where it is rendered.
Additional defenses
Use a restrictive Content Security Policy where practical, keep dependencies updated, and test endpoints with hostile input. Validation is useful but does not replace context-aware output encoding.