Andy A
Andy A

Reputation: 4301

getJSON not working (Beginner)

I am totally new to JSONP, AJAX and JQuery. I am trying to retrieve some data from a given URL, but it is not getting to my alert("Success!") after the getJSON. I'm struggling to work out why, or what to do next. Any advice?

(Note, I have replaced the actual URL for xx in this question)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns=" http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title> 
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script src="json-jquery.js" type="text/javascript"></script> 
<script src="json-jquery.js" type="text/javascript"></script>
<a href="json-data.php"></a>

<script>
   $(document).ready(function(){
       $.getJSON('http://xx.xxx.xxx.xx/getCourses.php?action=getUnpaid', function( data ) {
           alert("Success!");               
       });
   });
</script>

</head>
<body>
<a href="#" id="getdata-button">Get JSON Data</a>
<div id="showdata"></div>
</body>
</html> 

Upvotes: 0

Views: 146

Answers (1)

Guffa
Guffa

Reputation: 700192

The getJSON method doesn't do a JSONP request. To use JSONP you can use the ajax method, so that you can specify the data type:

$(document).ready(function(){
  $.ajax({
    url: 'http://xx.xxx.xxx.xx/getCourses.php?action=getUnpaid',
    dataType: 'jsonp',
    success: function( data ) {
      alert("Success!");               
    }
  });
});

A JSON request is made using the XMLHTTPRequest object, and is subject to the same origin policy. JSONP was introduced to circumvent this, and uses a script tag to load the resource. As a script can be loaded from a different domain, it's not subject to the same origin policy.

Upvotes: 2

Related Questions