How to write a $.getJSON call in $.ajax format?

How to write a $.getJSON call in $.ajax format?
0

#1

While completing the Local Weather project, I came across $.getJSON and $.ajax, and read the former is just shorthand for the latter.

They both look very differnt and I’m having trouble seeing how I would write my code below using $.ajax() instead of .getJSON(). I’m hoping understanding how both work will help clear up some confusion I have about how to make API calls in general.

function showPoints(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    // AJAX request
    var api = "https://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eec551a3788ea51493994e5edfb48781";

    $.getJSON(api, function(data) {
                var kTemp = data.main.temp;
                var type = data.weather[0].description;
                var city = data.name;
                var country = data.sys.country;
                var tempSwitch = true;

                // temperature conversions
                var fTemp = (kTemp * (9 / 5) - 459.67).toFixed(0);
                var cTemp = (kTemp - 273).toFixed(0);
                $("#temp").html(fTemp + "° " + "F");
                $("#temp").click(function() {
                    if (tempSwitch === false) {
                        $("#temp").html(cTemp + "° " + "C");
                        tempSwitch = true;
                    } else {
                        $("#temp").html(fTemp + "° " + "F");
                        tempSwitch = false;
                    }
                });
                $("#weather").html(city + ", " + country);

#2

Writing this:

$.getJSON(api, function(data){//everything inside your callback// })

is identical to writing this:

$.ajax({
  dataType: "json",
  url: api,
  data: data,
  success: function(data){//everything inside your callback //}
});

It is just that the latter gives you a lot more leverage on the settings you can use before/during and after your asynchronous request , http://api.jquery.com/jquery.getjson/