Apis-in-jquery

From Publication Station
Revision as of 12:16, 10 October 2023 by Arjensuijker (talk | contribs) (new page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

JavaScript allows you to pull information from external sources, and do something with it on your own website/app. For example, you can change the colors of your website based on the weather, or display the current number of humans in every country. This made even easier with Jquery, a library that makes writing JavaScript easier for the web.

1. Load Jquery

You can load the jquery library file directly from the cloud by pasting this line of code in the head of your HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

2. Create a JS file

First, create a new file, place it in the same folder as your html file and name it script.js. After that, place a link to it in the head of your document (underneath the jQuery link) like so:

<script src="script.js"></script>

3. Find a good API

There are API's for many things. A huge collection of them can be found here. lt is easiest to select one that requires no authorization and has no CORS protection. A relatively simple one to use is Open Meteo. This is an API that can be used to get past, present or future weather.

4. Call the API

In the script.js file that you just made, paste the following to test it out:

$( document ).ready(function() {
  $.getJSON( "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current=temperature_2m", function( result ) {
      $('body').html(result.current.temperature_2m); 
    });
});

On line 1, we tell jQuery to wait until everything is loaded. On line 2, we tel jQuery to get the info from Open Meteo in the Json format. On line 3, we place the temperature part of the results in the html of our body element.