Skip to content
jquery-ajax-json logo

jQuery AJAX with JSON - Best Practices Skill

jquery-ajax-json

Best practices for jQuery AJAX with JSON data handling including sending/receiving JSON, error handling, security (CSRF protection, XSS prevention), promise patterns, caching, and modern alternatives. Use when working with jQuery AJAX requests, implementing JSON APIs, troubleshooting AJAX issues,...

SKILL.md

Full skill instructions

jQuery AJAX with JSON - Best Practices Skill

Overview

Comprehensive guidance on using jQuery AJAX for sending and receiving JSON data with security, error handling, and modern best practices.

Core jQuery AJAX Methods

1. $.ajax() - Complete Control

```javascript $.ajax({ url: '/​api/​users', type: 'POST', dataType: 'json', contentType: 'application/​json', data: JSON.stringify({ name: 'John', email: '[email protected]' }), timeout: 10000, headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } }) .done(function(response) { /​* Handle success / }) .fail(function(xhr) { /​ Handle error / }) .always(function() { /​ Cleanup */ }); ```

2. $.getJSON() - GET Shorthand

```javascript $.getJSON('/​api/​users', { active: true }) .done(function(data) { console.log(data); }) .fail(function(xhr) { console.error(xhr); }); ```

Critical Best Practices

1. Always Use JSON.stringify() for Complex Data

❌ Bad: ```javascript $.ajax({ url: '/​api/​users', type: 'POST', data: { name: 'John', preferences: { theme: 'dark' } } // jQuery serializes as form data, not JSON! }); ```

✅ Good: ```javascript $.ajax({ url: '/​api/​users', type: 'POST', contentType: 'application/​json', data: JSON.stringify({ name: 'John', preferences: { theme: 'dark' } }) }); ```

2. Comprehensive Error Handling

```javascript $.ajax({ url: '/​api/​users' }) .done(function(data) { handleSuccess(data); }) .fail(function(xhr, textStatus, errorThrown) { let errorMessage = 'An error occurred';

if (xhr.status === 400) errorMessage = 'Invalid request';
else if (xhr.status === 401) { 
    errorMessage = 'Unauthorized';
    window.location.href = '/​login';
}
else if (xhr.status === 500) errorMessage = 'Server error';
else if (textStatus === 'timeout') errorMessage = 'Request timed out';

showErrorMessage(errorMessage);

}); ```

3. Security - CSRF Token Protection

```javascript // Global setup $(document).ready(function() { const csrfToken = $('meta[name="csrf-token"]').attr('content'); $.ajaxSetup({ headers: { 'X-CSRF-Token': csrfToken } }); }); ```

4. Input Validation

```javascript function createUser() { const userData = { name: $('#name').val().trim(), email: $('#email').val().trim() };

const errors = [];
if (!userData.name || userData.name.length < 2) 
    errors.push('Name must be at least 2 characters');
if (!isValidEmail(userData.email)) 
    errors.push('Invalid email');

if (errors.length > 0) {
    showErrors(errors);
    return;
}

$.ajax({
    url: '/​api/​users',
    type: 'POST',
    contentType: 'application/​json',
    data: JSON.stringify(userData)
});

} ```

5. Promise-Based API Service Layer

```javascript const UserAPI = { getAll: (filters) => $.ajax({ url: '/​api/​users', data: filters }), getById: (id) => $.ajax({ url: `/​api/​users/${id}` }), create: (data) => $.ajax({ url: '/​api/​users', type: 'POST', contentType: 'application/​json', data: JSON.stringify(data) }), update: (id, data) => $.ajax({ url: `/​api/​users/${id}`, type: 'PUT', contentType: 'application/​json', data: JSON.stringify(data) }) }; ```

Advanced Patterns

Request Cancellation

```javascript let currentRequest = null;

function searchUsers(query) { if (currentRequest) currentRequest.abort();

currentRequest = $.ajax({
    url: '/​api/​users/​search',
    data: { q: query },
    timeout: 5000
}).always(() => currentRequest = null);

} ```

Response Caching

```javascript const cache = {}; function getCachedData(url) { if (cache[url]) return $.Deferred().resolve(cache[url]); return $.ajax({ url }).done(data => cache[url] = data); } ```

Batch Requests

```javascript Promise.all([ $.getJSON('/​api/​stats'), $.getJSON('/​api/​orders'), $.getJSON('/​api/​revenue') ]).then(([stats, orders, revenue]) => { displayStats(stats); displayOrders(orders); displayRevenue(revenue); }); ```

Security Checklist

  • CSRF token included in state-changing requests
  • HTTPS used for sensitive data
  • User input escaped before display (use .text() not .html())
  • Input validation on client and server
  • Error messages don't expose sensitive info
  • Rate limiting implemented

Common Pitfalls to Avoid

  1. ❌ Not setting contentType: 'application/​json'
  2. ❌ No error handling (.fail)
  3. ❌ Using synchronous requests (async: false)
  4. ❌ Multiple enumerations of data
  5. ❌ Not cleaning up event handlers

Modern Alternative: Fetch API

```javascript async function createUser(userData) { try { const response = await fetch('/​api/​users', { method: 'POST', headers: { 'Content-Type': 'application/​json', 'X-CSRF-Token': document.querySelector('[name=csrf-token]').content }, body: JSON.stringify(userData) });

    if (!response.ok) throw new Error('Request failed');
    return await response.json();
} catch (error) {
    console.error(error);
    throw error;
}

} ```

More Security skills

supabase logo
Security

supabase

Handles the full Supabase workflow from schema changes to deployment, with built-in security guardrails that catch common traps like RLS...

2.7K 308.9K
View

Comprehensive guides and best practices for Neon Serverless Postgres, covering setup, connection methods, authentication, and platform APIs.

98 216.2K
View

Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.

462 163.8K
View

A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.

462 127.7K
View

Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security.

462 125.1K
View

Complete Better Auth server and client setup with database adapters, session management, plugins, and security configuration.

222 118.2K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View
cloudflare logo
Security

cloudflare

Complete Cloudflare platform integration with decision trees for compute, storage, AI, networking, security, and infrastructure-as-code.

3K 110.7K
View

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

253 103K
View
gws-gmail logo
Security

gws-gmail

Send, read, and manage Gmail messages, drafts, labels, and account settings.

31.2K 78.9K
View

Comprehensive website auditing across 230+ rules in 21 categories including SEO, performance, security, and accessibility.

94 72.3K
View
gws-shared logo
Security

gws-shared

Shared authentication, CLI syntax, and output formatting patterns for gws Google Workspace commands.

31.2K 63.4K
View

Security AI tools

StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
GeoSpy logo
Security

GeoSpy

GeoSpy: Pricing, Features, FAQs, and Alternatives for AI Teams

Free
View

Detect AI-generated voices to protect against audio fraud.

Paid
View

Ensure Your Content's Originality with AI Plagiarism Checker

Freemium
View
Img Upscaler logo
Security

Img Upscaler

Upscale images by 400% without quality loss

Freemium
View
AICheatCheck logo
Security

AICheatCheck

Accurately Detect AI-Generated Content with TheChecker.AI

Free
View
D
Security

Detect GPT

Chrome extension that detects and flags AI-generated content

Free
View