Jacob David Cunningham Jacob David Cunningham - 12 days ago 6
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:

<?php
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$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 */
<script>
function returnText(data) {
console.log('result: ' + data);
}
</script>


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

{"result":"10"}


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:

{"result":"10"}


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

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

    returnText({"result":"10"})
    

    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.)