JSON JSONP

Cross-domain data requests using JSONP technique

🌍 What is JSONP?

JSONP (JSON with Padding) is a technique for making cross-domain requests by wrapping JSON data in a JavaScript function call. It was used before CORS became widely supported.


// JSONP response format
callback({
    "name": "John",
    "age": 30,
    "city": "New York"
});
                                    

JSONP vs Regular JSON

🔒

Cross-Domain

Bypasses same-origin policy restrictions

📞

Callback Function

Data wrapped in a function call

⚠️

Security Concerns

Less secure than modern CORS

🔹 How JSONP Works

JSONP uses script tags to load data from other domains:

JSONP Process:

  1. Create a callback function
  2. Add script tag with callback parameter
  3. Server returns data wrapped in callback
  4. Browser executes the callback with data
<!DOCTYPE html>
<html>
<body>
    <div id="result"></div>

    <script>
        // Step 1: Define callback function
        function handleData(data) {
            document.getElementById('result').innerHTML = 
                `<h3>${data.name}</h3><p>Age: ${data.age}</p>`;
        }

        // Step 2: Create script tag
        const script = document.createElement('script');
        script.src = 'https://api.example.com/user?callback=handleData';
        document.head.appendChild(script);
    </script>
</body>
</html>

🔹 Simple JSONP Example

Basic JSONP implementation:

<!DOCTYPE html>
<html>
<body>
    <button onclick="loadWeather()">Get Weather</button>
    <div id="weather"></div>

    <script>
        // Callback function to handle weather data
        function showWeather(data) {
            const weatherDiv = document.getElementById('weather');
            weatherDiv.innerHTML = `
                <h3>Weather in ${data.city}</h3>
                <p>Temperature: ${data.temperature}°C</p>
                <p>Condition: ${data.condition}</p>
            `;
        }

        function loadWeather() {
            // Create script element for JSONP request
            const script = document.createElement('script');
            script.src = 'https://weather-api.example.com/current?city=London&callback=showWeather';
            document.head.appendChild(script);
            
            // Clean up script tag after use
            script.onload = function() {
                document.head.removeChild(script);
            };
        }
    </script>
</body>
</html>

Server Response (JSONP format):

showWeather({
    "city": "London",
    "temperature": 18,
    "condition": "Cloudy"
});

🔹 JSONP Helper Function

Create a reusable JSONP function:

function jsonp(url, callback) {
    // Generate unique callback name
    const callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    
    // Create global callback function
    window[callbackName] = function(data) {
        // Call user's callback with data
        callback(data);
        // Clean up
        delete window[callbackName];
        document.head.removeChild(script);
    };
    
    // Create script element
    const script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.head.appendChild(script);
}

// Usage example
jsonp('https://api.example.com/posts', function(data) {
    console.log('Received data:', data);
    // Process the data here
});

🔹 JSONP vs Modern Alternatives

Comparison with modern approaches:

JSONP Limitations:

  • Security: Executes arbitrary JavaScript code
  • Error Handling: Difficult to handle errors
  • HTTP Methods: Only supports GET requests
  • Debugging: Harder to debug than regular AJAX

Modern Alternative - CORS:

// Modern approach using fetch with CORS
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

🔹 When to Use JSONP

JSONP is mostly legacy, but still useful in specific cases:

Use JSONP when:

  • Working with old APIs that don't support CORS
  • Supporting very old browsers (IE8 and below)
  • The server specifically provides JSONP endpoints

Avoid JSONP when:

  • CORS is available (most modern cases)
  • Security is a major concern
  • You need POST/PUT/DELETE requests
  • Error handling is important

🧠 Test Your Knowledge

What does JSONP stand for?