0

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Skye
  • 230
  • 1
  • 3
  • 10

3 Answers3

3

Did you check the console? You might be suffering from a access-control-origin error

jQuery.getJSON - Access-Control-Allow-Origin Issue

Community
  • 1
  • 1
jakee
  • 18,486
  • 3
  • 37
  • 42
  • the fix here is to replace getJSON with a regular jQuery ajax call and set it's dataType to jsonp – jakee Jun 11 '12 at 13:41
  • that will only work if the site actually responds with a proper JSONP response; plain JSON won't work. – Pointy Jun 11 '12 at 13:44
  • The server has to support JSONP as well and `getJSON` will do a "JSONP request" if set up properly. – Felix Kling Jun 11 '12 at 13:45
1

You can not fetch JSON from another domain unless they support CORS because of the same origin policy.

Does the api support jsonp?

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

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) 
Spoeken
  • 2,549
  • 2
  • 28
  • 40