jon
jon

Reputation: 5

getJSON returns null or nothing at all due to jquery or php?

I created a php file to return data encoded with JSON and then used getJSON to read it. I am attempting to get info from one source and distribute it to multiple areas. I have changed the content-type also allowing all access with headers. At this point I am stuck. Any ideas how to get this working?

PHP

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');

$search_terms = curlData();
$json = array("term" => $search_term);   
echo $_GET['callback'] . "(" . json_encode($json) . ");";

the output for this php file is as follows:

({"term":"sandwich city"});

Here is the jQuery I am using to retrieve the json info

$.getJSON("http://MYWEBSITE.com/terms.php?callback", function(data) {
    alert(data);
});

Upvotes: 0

Views: 661

Answers (1)

Felix Kling
Felix Kling

Reputation: 816970

({"term":"sandwich city"}); is not valid JSONP. You are missing the function name.

Add =? to your URL, so that jQuery automatically generates a function to handle the response:

http://MYWEBSITE.com/terms.php?callback=?

From the documentation:

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.


Btw, if you send JSONP as response, setting the content type of the response to application/json is not correct. The response is simply JavaScript.

Furthermore, as you specified the Access-Control-Allow-Origin header, you don't have to use JSONP at all, you can make a normal AJAX call and return JSON.

Upvotes: 1

Related Questions