Programming

Basic example of using ajax with JSONP

25 September 2026 · 7 min read

Basic example of using ajax with JSONP

In the world of web development, fetching data from external sources is a common requirement. However, developers often encounter a significant hurdle: the Same-Origin Policy, a crucial security measure that prevents direct AJAX requests to a different domain. This policy is designed to protect users from malicious scripts but can complicate legitimate cross-domain data retrieval. Fortunately, for scenarios where server-side CORS (Cross-Origin Resource Sharing) is not an option, JSONP (JSON with Padding) offers a clever client-side workaround. Understanding a basic example of using .ajax() with JSONP is essential for any developer looking to expand their toolkit for robust web interactions.

Understanding Cross-Domain Data Requests and the Same-Origin Policy

The web is built on interconnected resources, yet security protocols often dictate how these connections can be made. At the heart of many web security models lies the Same-Origin Policy (SOP). This policy dictates that a web browser permits scripts contained in a first web page to access data in a second web page only if both web pages have the same origin. An origin is defined by the combination of URI scheme (protocol), hostname, and port number. For instance, a script on example.com cannot directly fetch data via an XMLHttpRequest (AJAX) from api.anothersite.com.

This restriction is fundamental for preventing various types of attacks, such as cross-site request forgery (CSRF) and information leakage. Without SOP, a malicious script on one website could potentially read sensitive data from another site that a user is logged into, like banking or email accounts. While crucial for security, SOP presents a challenge when legitimate applications need to communicate across different domains, such as consuming public APIs or integrating third-party services. This is where alternative techniques for cross-domain data fetching become invaluable, with JSONP being one of the earliest and most widely adopted solutions before the advent of CORS.

Modern web development increasingly relies on dynamic data loading, making these cross-origin issues frequent. While server-side solutions like CORS are often preferred for their flexibility and security, they require cooperation from the target server. When you’re working with external APIs that don’t support CORS, or when you need a quick client-side fix, understanding mechanisms like JSONP becomes a necessary skill. It’s about navigating the browser’s security landscape to achieve functionality without compromising user safety.

What is JSONP and Why Do We Use It?

JSONP, or “JSON with Padding,” is a technique used to bypass the Same-Origin Policy in web browsers. It leverages the fact that browsers do not enforce the Same-Origin Policy on <script> tags. When you include a script from another domain, the browser executes its content without restriction. JSONP exploits this by wrapping the JSON data in a JavaScript function call, effectively turning the data into executable code.

Here’s how it works: instead of making an XMLHttpRequest, JSONP requests dynamically inject a <script> tag into the DOM. The URL for this script tag points to the external domain and includes a special query parameter, typically named callback. The server, upon receiving this request, wraps its JSON response within the function name provided in the callback parameter and sends it back. When the browser loads this “script,” it executes the function with the JSON data as its argument, allowing your client-side code to access the cross-domain information. This elegant trick allows for seamless cross-domain data fetching where direct AJAX might fail.

JSONP is particularly useful when:

  • You need to fetch data from an external API that does not support CORS.
  • You require a client-side solution without server-side modifications to your own application.
  • The data source explicitly provides a JSONP endpoint.

However, it’s important to note its limitations:

  • JSONP only supports GET requests; it cannot be used for POST, PUT, or DELETE.
  • It lacks robust error handling compared to traditional AJAX requests.
  • There are security implications; if the JSONP endpoint is compromised, it could execute malicious code on your site. For a deeper dive into web security, consider learning more about various common web vulnerabilities.

According to Mozilla’s Web Docs, the Same-Origin Policy is “a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin.” While CORS (Cross-Origin Resource Sharing) is now the standard and preferred method for cross-origin requests, JSONP remains a viable fallback for legacy APIs or specific scenarios where CORS is unavailable. Understanding JSONP’s mechanism is key to appreciating both its utility and its inherent security considerations.

Infographic: A visual representation of the JSONP request flow, showing client, script tag injection, server response with callback, and client-side function execution.
A Basic Example of Using .ajax() with JSONP -------------------------------------------

Leveraging jQuery’s .ajax() method simplifies the process of making HTTP requests, including those using JSONP. The jQuery AJAX implementation for JSONP handles the dynamic script tag creation and the JSONP callback function automatically, making it incredibly straightforward for developers. Let’s walk through a practical example of fetching data from a public web API that supports JSONP.

Consider a scenario where we want to fetch current weather data from a hypothetical JSONP-enabled weather API. The API might expect a callback parameter in its URL. Here’s how you would structure your client-side scripting using jQuery:

 <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JSONP Example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> </head> <body> <h3>Current Weather Data (via JSONP)</h3> <div id="weather-data">Loading...</div> <script> $(document).ready(function() { $.ajax({ url: 'https://api.exampleweather.com/forecast?location=London&units=metric', // Hypothetical API endpoint dataType: 'jsonp', // This is the magic! jsonpCallback: 'handleWeatherResponse', // Optional: specify the callback function name success: function(response) { console.log('Weather data:', response); $('weather-data').html('<p>Location: ' + response.location + '</p>' + '<p>Temperature: ' + response.temperature + '°C&
<b>Question & Answer : </b><br></br><p>Please could someone help me work out how to get started with JSONP?</p> <p>Code:</p> $('document').ready(function() { var pm_url = 'http://twitter.com/status'; pm_url += '/user_timeline/stephenfry.json'; pm_url += '?count=10&callback=photos'; var photos = function (data) { alert(data); }; $.ajax({ url: pm_url, dataType: 'jsonp', jsonpCallback: 'photos', jsonp: false, }); });  <p>Fiddle: <a href="http://jsfiddle.net/R7EPt/6/">http://jsfiddle.net/R7EPt/6/</a></p> <p>Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).</p> <p>thanks. </p>
<br></br><p><strong>JSONP</strong> is really a simply trick to overcome <strong>XMLHttpRequest</strong> same domain policy. (As you know one cannot send <strong>AJAX (XMLHttpRequest)</strong> request to a different domain.)</p> <p>So - instead of using <strong>XMLHttpRequest</strong> we have to use <strong>script</strong> HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?</p> <p>Thing is - turns out <strong>script</strong> tags can be used in a fashion similar to <strong>XMLHttpRequest</strong>! Check this out:</p> script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://www.someWebApiServer.com/some-data";  <p>You will end up with a <strong>script</strong> segment that looks like this after it loads the data:</p> <script> {['some string 1', 'some data', 'whatever data']} </script>  <p>However this is a bit inconvenient, because we have to fetch this array from <strong>script</strong> tag. So <strong>JSONP</strong> creators decided that this will work better (and it is):</p> script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";  <p>Notice <em>my_callback</em> function over there? So - when <strong>JSONP</strong> server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:</p> my_callback({['some string 1', 'some data', 'whatever data']});  <p>See where the profit is: now we get automatic callback (<em>my_callback</em>) that'll be triggered once we get the data. That's all there is to know about <strong>JSONP</strong>: it's a callback and script tags.</p> <hr></hr> <p><strong>NOTE:<br></br> These are simple examples of JSONP usage, these are not production ready scripts.</strong></p> <p><strong>RAW JavaScript demonstration (simple Twitter feed using JSONP):</strong></p> <html> <head> </head> <body> <div id = 'twitterFeed'></div> <script> function myCallback(dataWeGotViaJsonp){ var text = ''; var len = dataWeGotViaJsonp.length; for(var i=0;i<len;i++){ twitterEntry = dataWeGotViaJsonp[i]; text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>' } document.getElementById('twitterFeed').innerHTML = text; } </script> <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script> </body> </html>  <p><br></br> <strong>Basic jQuery example (simple Twitter feed using JSONP):</strong></p> <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script> $(document).ready(function(){ $.ajax({ url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10', dataType: 'jsonp', success: function(dataWeGotViaJsonp){ var text = ''; var len = dataWeGotViaJsonp.length; for(var i=0;i<len;i++){ twitterEntry = dataWeGotViaJsonp[i]; text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>' } $('#twitterFeed').html(text); } }); }) </script> </head> <body> <div id = 'twitterFeed'></div> </body> </html>  <p><br></br> <strong>JSONP</strong> stands for <strong>JSON with Padding</strong>. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)</p>