Dylan Kidd Dylan Kidd - 5 months ago 23
Javascript Question

Reading from a online data API using AJAX/JSON

Sorry if this is a foolish question, I'm just finding hard to wrap my head around how to do this without just running out and learning ten million frameworks...

I want to query an online database (specifically https://data.qld.gov.au/dataset/fireworks/resource/346d58fc-b7c1-4c38-bf4d-c9d5fb43ce7b).

The end goal is to be able to display this information on a website. My first idea was to just create a small website locally and take one of their ajax queries, but it won't connect.

What is the simplest way to query a data API?
(I'm working with HTML/CSS/JS, and have started learning Node.js, JSON data and AJAX, but I'm new).

I have right now a website that I'm just opening locally (i.e. it's address is file:///C:/Users/Dylan/fireworks/getinfo.html) and very simple HTML and javascript copied from the website. But the alert always returns undefined, telling me that it's not actually trying to connect. What am I missing here and why?



$(document).ready(function(){
var data = {
resource_id: '346d58fc-b7c1-4c38-bf4d-c9d5fb43ce7b', // the resource id
limit: 5, // get 5 results
q: 'jones' // query for 'jones'
};

console.log("got here");
$.ajax({
url: 'https://data.qld.gov.au/api/action/datastore_search',
data: data,
dataType: 'jsonp',
success: function(data) {
alert('Total results found: ' + data.result.total)
}
});

});

<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src = "getinfo.js"></script>
</head>
<body>
<h1> I hate myself </h1>
</body>
</html>





I know it sounds like too broad of a question, if your answers are broad that's okay. I just want to know what I need to learn in order to complete the simple task of retrieving information off of an online database, and why I can't just query it from my computer?

Thanks!

Answer

You were so close!! You were just trying to get a count from the result variable but thats a hashtable/dictionary rather than an array. Try getting the count by calling the length method on result.records

Note that I removed the q param so we actually get some records back

$(document).ready(function(){
  var data = {
    resource_id: '346d58fc-b7c1-4c38-bf4d-c9d5fb43ce7b', // the resource id
    limit: 5, // get 5 results
    // q: 'jones' // query for 'jones' remove this so we actually get some records
  };

  console.log("got here");
  $.ajax({
    url: 'https://data.qld.gov.au/api/action/datastore_search',
    data: data,
    dataType: 'jsonp',
    success: function(successData) {
      alert('Total results found: ' + successData.result.records.length)
    }
  });

});
<html>
<head>
	<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
	<script src = "getinfo.js"></script> 
</head>
<body>
	<h1> I am a golden god </h1>
</body>
</html>