Reputation: 230
I have the following jquery code:
$(document).ready(function()
{
$('button').click(function()
{
$.getJSON('http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/server/status?output=json', function(json)
{
alert("Entered getJSON");
$("#output").append("working...");
if(json.status.indexOf("success")===0)
{
alert("success");
$.each(json.results, function(i, data)
{
$("#output").append(data.text);
});
}else
{
alert("Failed to load url");
}
});
});
});
The json that is pulled from the url looks like:
{"worldServerStatus": {
"customMessage": "",
"lastChangedDate": {
"date": 31,
"day": 4,
"hours": 17,
"minutes": 48,
"month": 4,
"nanos": 0,
"seconds": 32,
"time": 1338486512000,
"timezoneOffset": 0,
"year": 112
},
"localizedMessage": "The servers are currently up and running.",
"message": "ALL_SYSTEMS_GO",
"status": "UP"
}}
My jquery just refuses to enter the $.getJSON function, the "enetered getJSON" alert doesn't fire.
What is wrong?
Solved. Thank you all :)
Upvotes: 0
Views: 1734
Reputation: 2598
I don't think you will be able to do this. For cross domain ajax requests the api provider have to use jsonp. What you can do is create a php file for the request. Lets call the file request.php
<?php
/* gets the data from a URL */
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$query = $_SERVER['QUERY_STRING'];
$url = ('http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/server/status?'.$query);
echo get_data($url);
?>
Then in your javascript
$.getJSON('http://myserver.com/request.php?output=json', function(json)
Upvotes: 0
Reputation: 207527
You can not fetch JSON from another domain unless they support CORS because of the same origin policy.
Does the api support jsonp?
Upvotes: 1
Reputation: 18566
Did you check the console? You might be suffering from a access-control-origin error
jQuery.getJSON - Access-Control-Allow-Origin Issue
Upvotes: 3