Simple jQuery, PHP and JSONP example?

Simple jQuery, PHP and JSONP example?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Converting jQuery POSTs to JSONP: Handling Cross-Origin Data

When dealing with cross-origin requests, the browser’s Same-Origin Policy acts as a strict gatekeeper. It prevents JavaScript running on example.com from reading the response of a request sent to mysite.com, even if both sites are served over HTTPS. Your standard jQuery .post() or .ajax() calls will fail silently in the console with a CORS error when you attempt to read the response body directly.

While modern browsers support CORS headers to solve this, JSONP remains a viable strategy for older environments or specific legacy integrations where modifying server headers is impossible. The mechanism relies on a clever loophole: it doesn't use XMLHttpRequest at all. Instead, it uses standard <script> tags, which browsers do not restrict by origin.

To convert your example from a simple POST to a working JSONP request, you must fundamentally change how data is sent and received. You cannot send raw data via $.post in this context; the browser expects a function call pattern.

The Client-Side Changes

On the client side, jQuery provides the .jsonp() method specifically for this scenario. Unlike standard AJAX, this method automatically appends a callback parameter to your URL and configures the request to handle the response as a script execution rather than JSON.

Here is how you adapt your original code:

$.ajax({
    url: 'http://MySite.com/MyHandler.php',
    data: {
        firstname: 'Jeff'
    },
    dataType: 'jsonp',
    jsonp: 'callback', // Name of the callback parameter
    success: function (res) {
        alert('Your name is ' + res);
    }
});

Notice the dataType: 'jsonp' flag. This tells jQuery to construct the request URL like MyHandler.php?firstname=Jeff&callback=jQuery123456. The exact callback function name varies by jQuery version, but the structure remains consistent.

The Server-Side Implementation

The PHP handler needs to recognize this special parameter and wrap your response in a function call matching that name. In your original snippet, you were echoing plain text or checking conditions directly. For JSONP, the output must be valid JavaScript code.

Here is the corrected PHP logic:

<?php
// Define the callback function name from the query string
$callback = isset($_GET['callback']) ? $_GET['callback'] : '';

// Retrieve and sanitize the input
$fname = isset($_GET['firstname']) ? $_GET['firstname'] : '';

// Logic to determine the response
if ($fname === 'Jeff') {
    $responseName = 'Jeff Hansen';
} else {
    // Handle cases where the name doesn't match or is missing
    $responseName = 'Guest'; 
}

// Output the JSONP formatted string
// We only wrap the output if a callback parameter exists
if (!empty($callback)) {
    echo $callback . '(' . $responseName . ');' . "\n";
} else {
    // Fallback for standard requests or debugging
    echo json_encode(['name' => $responseName]);
}
?>

Key technical details here include using $_GET instead of $_POST. Since the data is passed via URL parameters to form a function call, it must be query string arguments. Additionally, the output must end with a semicolon to ensure valid JavaScript syntax.

Handling HTML and Security Implications

You asked if storing HTML in the result would work. Technically, yes, but you must escape the content properly within the PHP logic before echoing it. If you echo raw HTML containing quotes or parentheses directly into the function arguments, you will break the JavaScript parsing, resulting in a syntax error.

However, using JSONP for returning arbitrary HTML is generally discouraged. Because the browser executes the response as code, any unescaped HTML tags inside your data payload could lead to Cross-Site Scripting (XSS) vulnerabilities if an attacker controls the input. If you intend to return complex structures or HTML fragments, consider switching to a modern CORS-enabled approach where you can safely return JSON and manipulate the DOM via standard AJAX methods on the client side.

Why This Matters Today

While the IBM article from your source material explains the theory well, the practical application requires strict adherence to the callback pattern. The main trade-off is that JSONP only supports GET requests. You cannot send POST or PUT data in a true JSONP payload because the request method must be GET for <script> tags to work. If your use case requires sending sensitive data or modifying server state, CORS with proper headers on the backend remains the superior, more secure solution.

Our network