AJAX Advanced Options

Back

Loading concept...

jQuery AJAX Advanced Options: The Master Chef’s Kitchen 🍳

Imagine you’re in a super fancy restaurant kitchen. The basic AJAX call is like ordering food - you say what you want, and it comes. But what if you want to control HOW it’s cooked, WHEN to check on it, and WHAT to do if something goes wrong?

That’s what AJAX Advanced Options are all about - being the master chef who controls everything!


🎯 Our Kitchen Tools (What We’ll Learn)

Tool What It Does
Configuration Options Your recipe settings
Callback Functions Kitchen timers that ring
Global Events Restaurant-wide announcements
Error Handling What to do when things burn
Serialize Methods Packing ingredients neatly
CORS Getting ingredients from other stores
JSON Data Special ingredient containers
FormData Big shopping bags for files

1️⃣ AJAX Configuration Options

The Recipe Card 📋

When you cook (make an AJAX call), you can set many options - like a detailed recipe card!

$.ajax({
  url: '/api/food',
  method: 'POST',
  data: { dish: 'pizza' },
  timeout: 5000,
  cache: false,
  async: true,
  contentType: 'application/json',
  dataType: 'json'
});

What Each Setting Means

Option Simple Meaning Example
url Where to send request '/api/users'
method GET (ask) or POST (give) 'POST'
data What you’re sending { name: 'Tom' }
timeout How long to wait (ms) 5000 (5 seconds)
cache Remember old answers? false
async Wait or keep working? true
contentType What format is data? 'application/json'
dataType What format do you expect back? 'json'

Real Example: Like Ordering Pizza 🍕

$.ajax({
  url: '/api/order',
  method: 'POST',
  data: { pizza: 'pepperoni' },
  timeout: 30000,
  cache: false,
  headers: {
    'Authorization': 'Bearer mytoken'
  }
});

Think of it like this: You’re ordering pizza. You tell them:

  • WHERE to deliver (url)
  • WHAT pizza (data)
  • HOW LONG you’ll wait (timeout)
  • Don’t give me yesterday’s pizza (cache: false)

2️⃣ Callback Functions

Your Kitchen Timers 🔔

Callbacks are like timers that ring at different moments during cooking!

graph TD A["Start Request"] --> B["beforeSend"] B --> C["Send to Server"] C --> D{Success?} D -->|Yes| E["success callback"] D -->|No| F["error callback"] E --> G["complete callback"] F --> G

All the Callbacks

$.ajax({
  url: '/api/data',

  beforeSend: function(xhr) {
    console.log('Starting...');
  },

  success: function(data) {
    console.log('Got it!', data);
  },

  error: function(xhr, status, error) {
    console.log('Oops!', error);
  },

  complete: function(xhr, status) {
    console.log('All done!');
  }
});

When Each One Rings

Callback When It Happens Like…
beforeSend Just before sending “I’m about to call the restaurant”
success Got good response “My food arrived hot!”
error Something went wrong “They burned my order!”
complete Always runs at end “Meal time is over”

Fun Trick: Show Loading Spinner

$.ajax({
  url: '/api/slow-data',

  beforeSend: function() {
    $('#spinner').show();
  },

  complete: function() {
    $('#spinner').hide();
  },

  success: function(data) {
    $('#result').html(data);
  }
});

3️⃣ Global AJAX Events

Restaurant-Wide Announcements 📢

What if you want EVERY request to show a loading spinner? You’d need to copy-paste code everywhere… OR use global events!

// This runs for ALL AJAX calls!
$(document).ajaxStart(function() {
  $('#loading').show();
});

$(document).ajaxStop(function() {
  $('#loading').hide();
});

All Global Events

Event When It Fires
ajaxStart First request begins
ajaxStop Last request ends
ajaxSend Before each request
ajaxSuccess After each success
ajaxError After each error
ajaxComplete After each request ends

Complete Example

$(document)
  .ajaxStart(function() {
    console.log('Kitchen opened!');
    $('#spinner').show();
  })
  .ajaxStop(function() {
    console.log('Kitchen closed!');
    $('#spinner').hide();
  })
  .ajaxError(function(e, xhr, settings) {
    console.log('Error at:', settings.url);
  });

Turn Off Global Events for One Request

$.ajax({
  url: '/api/secret',
  global: false  // Won't trigger global events
});

4️⃣ Error Handling

When Things Go Wrong 🔥

Errors happen! A good chef always has a backup plan.

Types of Errors

graph TD A["Error Types"] --> B["Network Error"] A --> C["Server Error"] A --> D["Parse Error"] A --> E["Timeout"] B --> F["No internet connection"] C --> G["404, 500, etc."] D --> H["Bad JSON format"] E --> I["Took too long"]

The Error Callback Explained

$.ajax({
  url: '/api/data',
  error: function(xhr, status, error) {
    // xhr = the request object
    // status = 'error', 'timeout', etc
    // error = error message

    console.log('Status code:', xhr.status);
    console.log('Status text:', status);
    console.log('Error:', error);
  }
});

Smart Error Handling

$.ajax({
  url: '/api/data',
  timeout: 5000,

  error: function(xhr, status) {
    if (status === 'timeout') {
      alert('Too slow! Try again.');
    } else if (xhr.status === 404) {
      alert('Page not found!');
    } else if (xhr.status === 500) {
      alert('Server is broken!');
    } else {
      alert('Something went wrong!');
    }
  }
});

Using .fail() with Promises

$.ajax('/api/data')
  .done(function(data) {
    console.log('Success!', data);
  })
  .fail(function(xhr) {
    console.log('Failed!', xhr.status);
  })
  .always(function() {
    console.log('All done!');
  });

5️⃣ Serialize Methods

Packing Your Ingredients Neatly 📦

When you have a form with many fields, how do you send ALL of them easily?

.serialize() - Makes a String

<form id="myForm">
  <input name="user" value="Tom">
  <input name="age" value="10">
</form>
var data = $('#myForm').serialize();
// Result: "user=Tom&age=10"

.serializeArray() - Makes an Array

var data = $('#myForm').serializeArray();
// Result: [
//   { name: "user", value: "Tom" },
//   { name: "age", value: "10" }
// ]

Which One to Use?

Method Output Best For
.serialize() "a=1&b=2" Simple POST requests
.serializeArray() [{name,value}] When you need to modify data

Real Example

$('#myForm').submit(function(e) {
  e.preventDefault();

  $.ajax({
    url: '/api/save',
    method: 'POST',
    data: $(this).serialize(),
    success: function() {
      alert('Saved!');
    }
  });
});

6️⃣ Cross-Domain AJAX and CORS

Getting Ingredients from Other Stores 🏪

Normally, your website can only talk to its own server. This is like a rule: “Only shop at your own store!”

But sometimes you need ingredients from another store (another domain). That’s where CORS comes in!

The Problem

// Your site: mysite.com
// You want data from: api.othersite.com

// This might be BLOCKED! 🚫
$.ajax({
  url: 'https://api.othersite.com/data'
});

What is CORS?

CORS = Cross-Origin Resource Sharing

It’s like the other store saying: “Yes, I’ll let customers from your store shop here!”

graph LR A["Your Site"] -->|Request| B["Other Server"] B -->|"CORS Header:<br>You're allowed!"| A

How to Enable CORS (Server Side)

The other server must add this header:

Access-Control-Allow-Origin: *

Or specifically:

Access-Control-Allow-Origin: https://mysite.com

Client-Side Settings

$.ajax({
  url: 'https://api.other.com/data',
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  }
});

JSONP (Old Solution)

Before CORS, we used JSONP (only works with GET):

$.ajax({
  url: 'https://api.other.com/data',
  dataType: 'jsonp',
  success: function(data) {
    console.log(data);
  }
});

7️⃣ AJAX with JSON Data

Special Ingredient Containers 🥡

JSON is like a organized lunchbox - everything in its place!

Sending JSON

$.ajax({
  url: '/api/users',
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({
    name: 'Tom',
    age: 10,
    hobbies: ['games', 'coding']
  }),
  success: function(response) {
    console.log(response);
  }
});

Important: JSON.stringify()

You MUST convert your object to a string:

// Wrong ❌
data: { name: 'Tom' }

// Right ✅
data: JSON.stringify({ name: 'Tom' })

Receiving JSON

$.ajax({
  url: '/api/users',
  dataType: 'json',  // Tells jQuery to parse response
  success: function(users) {
    // users is already a JS object!
    users.forEach(function(user) {
      console.log(user.name);
    });
  }
});

Shortcut: $.getJSON()

$.getJSON('/api/users', function(users) {
  console.log(users);
});

8️⃣ AJAX with FormData

Big Shopping Bags for Files 🛒

What if you want to send a file (like a photo)? Regular forms can’t do it. You need FormData!

Creating FormData

var formData = new FormData();
formData.append('name', 'Tom');
formData.append('photo', fileInput.files[0]);

Sending Files with AJAX

var formData = new FormData();
formData.append('avatar', $('#file')[0].files[0]);
formData.append('username', 'tom');

$.ajax({
  url: '/api/upload',
  method: 'POST',
  data: formData,
  processData: false,  // Don't process!
  contentType: false,  // Don't set type!
  success: function(response) {
    alert('Uploaded!');
  }
});

Why These Settings?

Setting Why Needed
processData: false Don’t convert FormData to string
contentType: false Let browser set the right boundary

From an Existing Form

<form id="uploadForm">
  <input type="text" name="title">
  <input type="file" name="document">
</form>
var formData = new FormData($('#uploadForm')[0]);

$.ajax({
  url: '/api/upload',
  method: 'POST',
  data: formData,
  processData: false,
  contentType: false
});

Upload Progress Bar 📊

$.ajax({
  url: '/api/upload',
  method: 'POST',
  data: formData,
  processData: false,
  contentType: false,
  xhr: function() {
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener('progress',
      function(e) {
        if (e.lengthComputable) {
          var percent = (e.loaded / e.total) * 100;
          $('#progress').css('width', percent + '%');
        }
      }
    );
    return xhr;
  }
});

🎯 Quick Summary

graph LR A["AJAX Advanced"] --> B["Config Options"] A --> C["Callbacks"] A --> D["Global Events"] A --> E["Error Handling"] A --> F["Serialize"] A --> G["CORS"] A --> H["JSON"] A --> I["FormData"] B --> B1["timeout, cache,&lt;br&gt;headers, etc."] C --> C1["beforeSend, success,&lt;br&gt;error, complete"] D --> D1["ajaxStart, ajaxStop,&lt;br&gt;ajaxError"] E --> E1[".fail, status codes"] F --> F1[".serialize,&lt;br&gt;.serializeArray"] G --> G1["Cross-domain,&lt;br&gt;JSONP"] H --> H1["JSON.stringify,&lt;br&gt;$.getJSON"] I --> I1["File uploads,&lt;br&gt;progress"]

🚀 You’re Now an AJAX Master Chef!

You’ve learned to:

  • ✅ Configure every detail of your requests
  • ✅ React to different moments with callbacks
  • ✅ Handle all requests with global events
  • ✅ Catch and handle errors gracefully
  • ✅ Pack form data efficiently
  • ✅ Cross boundaries with CORS
  • ✅ Work with JSON like a pro
  • ✅ Upload files with FormData

Remember: Like a master chef, the more you practice, the better you get! 🍳✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.