Jacob David Cunningham Jacob David Cunningham - 1 year ago 75
PHP Question

What's wrong with my JSONP code attempt?

So I have a script on the external server I'm trying to get data from.

It's a PHP script called test.php and it has the following inside:

$parts = parse_url($url);
parse_str($parts['query'], $query);
$limit = $query['limit'];
$return_array["result"] = $limit;
echo json_encode($return_array);

So then I send a call to that server using the following:

/* this is included in head */
<script src="http://some-website.com/get-text/index.php?limit=10&q=returnText"></script>

/* in Body */
function returnText(data) {
console.log('result: ' + data);

When you go to that php page by itself, the output is


But when I run the file that has the JavaScript code I get an error:

index.php?limit=10&q=returnText:1 Uncaught SyntaxError: Unexpected token :

when you click on the link on the right of this error line I see this:


With a red-underline starting from the colon and going to the right.

I saw somewhere to make sure that JSONP is enabled, it doesn't seem like an actual server configuration or something.

What am I doing wrong?

Answer Source

There are two problems:

  1. In JSONP, you must wrap the JSON in a function call; that's how JSONP works.

    Given your URL, your PHP code's response should be


    Get the q parameter from the query parameters and use that in the response as the function name. (The usual name of that parameter is callback, although you can call it something else if you like.)

  2. You've said that the script element calling the PHP file is in the head, but the script element defining the returnText callback is in the body. That won't work with the script element you've shown, because the one in head will stop all parsing of the page, make the browser wait until it's retrieved, and then only when it's retrieved and run will it allow parsing to continue. That means the returnText function won't exist yet. It would make more sense to move the script querying the JSONP to after the script containing the callback function. (And you might consider async or defer on it.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download