W3docs

Simple jQuery, PHP and JSONP example?

jQuery:

jQuery:

Example of making a JSONP request to a PHP file - jQuery code

$.ajax({
  url: "your_php_file.php",
  dataType: "jsonp",
  success: function(response) {
    console.log(response);
  },
  error: function(xhr, status, error) {
    console.error("Request failed:", status, error);
  }
});

PHP:

Example of making a JSONP request to a PHP file - PHP code

<?php
header('Content-Type: application/javascript');
$callback = $_GET['callback'] ?? 'callback';
echo $callback . '(' . json_encode(["key" => "value"]) . ');';
?>

This example uses jQuery's $.ajax() function to make a JSONP request to a PHP file, which returns a JSON-encoded response. The success function is called when the request is successful and the response is passed as an argument. The error function handles any request failures.

JSONP is a technique that allows cross-domain requests by injecting a ```<script>``` tag into the HTML document, rather than using the `XMLHttpRequest` object. It works by creating a script tag whose source points to the target URL. The PHP file returns a JavaScript object wrapped in a callback function specified by the client.

Note: JSONP is largely considered obsolete. For modern cross-domain requests, CORS (Cross-Origin Resource Sharing) is the recommended standard.