← Back to jQuery Course | Chapter 10: Advanced AJAX | Lesson 4 of 4

Cross-Domain Requests JSONP and CORS

A browser normally restricts requests between different origins. CORS is the standard way for a server to allow cross-origin requests.
Syntax
javascript
$.ajax({
  url: "url",
  dataType: "jsonp",
  success: function (data) { /* ... */ }
});

1. What Is Cross-Domain AJAX?

A cross-domain AJAX request targets a different origin — a different domain, protocol, or port — than the page that made it, and browsers restrict these by default as a security measure. Without the server's cooperation, JavaScript running on one site can't freely read responses from another.

Example: 1. What Is Cross-Domain AJAX?

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "https://api.example.com/data",
        success: function(data) { $("#output").append($("<div>").text(JSON.stringify(data))); },
        error: function() { $("#output").append($("<div>").text("Blocked by browser CORS restrictions")); }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

2. CORS Basics

CORS (Cross-Origin Resource Sharing) is controlled entirely by the server through HTTP response headers like Access-Control-Allow-Origin; jQuery cannot bypass a browser's CORS restriction on its own. If a request is being blocked, the fix has to happen on the server you're calling, not in your jQuery code.

Example: 2. CORS Basics

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      // CORS is controlled by the server's response headers, not by jQuery
      $.ajax({
        url: "https://api.example.com/data",
        success: function(data) { $("#output").text(JSON.stringify(data)); }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

3. JSONP with jQuery

JSONP is an older technique for making cross-domain GET requests that predates CORS, working by loading a script tag instead of a real AJAX request. It only works with servers that specifically support the JSONP response format, and it can't be used for POST requests.

Example: 3. JSONP with jQuery

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "https://api.example.com/data",
        dataType: "jsonp",
        success: function(data) { $("#output").text(JSON.stringify(data)); }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

4. CORS with Credentials

Credentialed CORS requests can send cookies or other credentials along with a cross-origin call, but only when both the client sets withCredentials and the server explicitly allows it via Access-Control-Allow-Credentials. Use this only when the request genuinely needs the user's session, since it loosens a security boundary.

Example: 4. CORS with Credentials

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "https://api.example.com/data",
        xhrFields: { withCredentials: true },
        success: function(data) { $("#output").text(JSON.stringify(data)); }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

5. CORS vs JSONP

CORS is the modern, standard choice for cross-origin AJAX and supports all HTTP methods, while JSONP is limited to GET requests and only works if the target server built in JSONP support. For any new project, CORS is almost always the right choice over JSONP.

Example: 5. CORS vs JSONP

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      // CORS: modern, all HTTP methods. JSONP: legacy, GET only, needs server support
      $.ajax({url: "https://api.example.com/data", dataType: "json"});
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming $.ajax() to another domain just works, when the browser blocks the response unless the server sends Access-Control-Allow-Origin.
  2. Trying JSONP with method: "POST", when JSONP only works with GET because it loads a <script> tag.
  3. Setting dataType: "jsonp" for a server that does not wrap its response in the callback function, so the callback never runs.
Chapter Summary
  • ajax() is the low-level method that gives full control over requests.
  • Headers and status codes can be processed, and global hooks listen to all AJAX activity.
  • Cross-domain requests use JSONP and CORS.
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.