2

In the following code, there is a url which returns results in JSON format. I want to read the JSON and parse it in my code. However, when I run the code, the result is empty. Seems I can not send Cross Domain AJAX requests!

I also tried to include Access-Control-Allow-Credentials: true in the code by writing xhrFields: { withCredentials: true }, crossDomain: true,, but again it does not work. It gives the following error: Error: jQuery111209679192922043036_1428845360268 was not called

  $.ajax(
{
 url:"http://ec.europa.eu/semantic_webgate/query/sparql?dataset=rasff&format=json&limit=10&query=select%20?p%20where%20+{+?s%20?p%20?o+}",
 dataType:'jsonp',
 type:"GET",
 
 success:function(data)
 {
  alert("Data from Server"+JSON.stringify(data));
 },
 error:function(jqXHR,textStatus,errorThrown)
 {
  alert("You can not send Cross Domain AJAX requests : "+errorThrown);
 }
});

How can I write a jsonp code to read this url ?

Enayat
  • 3,904
  • 1
  • 33
  • 47

1 Answers1

4

For JSONP, set your dataType:'json' to dataType:'jsonp'. Also, your sever needs to know about JSONP. A true JSONP-aware web service will read in the mandatory ?callback=? parameter of your URL.

Here is what a proper JSONP response looks like: http://ip.jsontest.com/?callback=methodName with response:

methodName({"ip": "151.194.190.31"});

Solution 1 - JSONP with callback

Find out if that URL supports JSONP and a callback name. If so, use a callback parameter and use JSONP. No CORS problem. Here is a sample Fiddle.

More info: jquery + jsonp return syntax error even when the response is json

Solution 2 - Permit CORS and use plain JSON

Add the Access-Control-Allow-Origin: * to the response from that URL (if you can control it), and process it as a JSON response (not JSONP).

Solution 3 - DIY JSONP wrapper

If that URL doesn't support JSONP, and it doesn't allow CORS, then you can cheat by using some server-side code to scrape the JSON results of that URL, then wrap the JSON in a callback function, set the header to Access-Control-Allow-Origin: *, and return the results to your AJAX JSONP script. Pretty neat, huh?

Oh, and here you go:

<?php
// xss-service.php - Bare-bones demo by @Drakes
$callback = isset($_GET["callback"]) ? $_GET["callback"] : "?";

$json = file_get_contents('http://ec.europa.eu/semantic_webgate/query/sparql?dataset=rasff&format=json&limit=10&query=select%20?p%20where%20%20%7B%20?s%20?p%20?o%20%7D');

header('Access-Control-Allow-Origin: *');
header("Content-type: application/json");
echo $callback . "(" . $json . ");";
?>

Solution 4 - JSONP Proxy service

If you just need to get this working now, you can use an online JSONP proxy service, for example, Yahoo's YQL service. Then, using your URL with no JSONP, and no CORS, you can do:

var theUrl = "http://ec.europa.eu/semantic_webgate/query/sparql?dataset=rasff&format=json&limit=10&query=select%20?p%20where%20%20%7B%20?s%20?p%20?o%20%7D";

var yql = 'http://query.yahooapis.com/v1/public/yql?'
        + 'q=' + encodeURIComponent('select * from json where url=@url')
        + '&url=' + encodeURIComponent(theUrl)
        + '&format=json&callback=?';

$.getJSON(yql,
  function (data) {
    alert(JSON.stringify(data));
  }
);

Demo: http://jsfiddle.net/L4foze7t/

Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94
  • Thanks for your response. I get the following error: `Error: jQuery111209679192922043036_1428845360268 was not called` – Enayat Apr 12 '15 at 13:30
  • Please see the link I posed. It shows examples of your problem and how to fix it – Drakes Apr 12 '15 at 13:35
  • So is there any way to read and process the JSON from the mentioned URL? – Enayat Apr 12 '15 at 13:36
  • Is it your URL? Do you control it? Right now it's not responding with the `Access-Control-Allow-Origin: *` header... so no. – Drakes Apr 12 '15 at 13:37
  • This is what a proper JSONP response looks like: http://ip.jsontest.com/?callback=methodName – Drakes Apr 12 '15 at 13:39
  • No, it is not my URL and I can not control it. AFAIK, with java, we can store a remote JSON file through a JSON API. I wanted to simulated it through JSONP or CORS. – Enayat Apr 12 '15 at 13:41
  • @Enayat — The API has to configure CORS and JSONP has to be set up at both ends. – Quentin Apr 12 '15 at 13:47
  • @Enayat I've written two solutions for you – Drakes Apr 12 '15 at 13:52
  • @Drakes Thanks for the solution and I think the target only supports Json and not JSONP :-( As I mentioned, it is kind of query result. – Enayat Apr 12 '15 at 14:20
  • I haven't given up on you! I'll add a 3rd solution for you – Drakes Apr 12 '15 at 14:26
  • Your third solution gave me the following error failed to open stream: `HTTP request failed! HTTP/1.1 502 Bad Gateway` – Enayat Apr 12 '15 at 15:22
  • That's not me, mate, it's on their side. 502 is not a code error. – Drakes Apr 12 '15 at 15:26
  • Try your code with my url `http://main.xfiddle.com/e864a11b/xss-service.php?callback=?` exactly as typed in your ajax code – Drakes Apr 12 '15 at 15:28
  • Man!, I know that my code works with some other URLs including yours and now I know that the mentioned target does not support JSONP. The question is how can I get the Json data from this specific URL? The result is there, open, and ready to use. Doesn't exist any solution to get the JSON result through this URL in javascript? Also, I don't want to use php. – Enayat Apr 12 '15 at 15:35
  • With only Javascript? No way! Not with your restrictions in place. What's wrong with solution 3? If you are really desperate, there are online services that can wrap JSON for you. Example - https://developer.yahoo.com/yql/guide/yql_url.html – Drakes Apr 12 '15 at 15:57
  • There is now a solution 4. Man, you are making me do a lot of work – Drakes Apr 12 '15 at 16:10
  • Man, It worked finally! You did a really great job. Many thanks for your time and effort! I wanted to tell you write down the solution 4, which I see you did. Thank you!!! – Enayat Apr 12 '15 at 16:54
  • No problem! I'm glad this effort helped. Kindly remember to accept the answer :) – Drakes Apr 14 '15 at 10:11