Curious about what others see as the best way to architect making an API call that depends on the response of another API call in jQuery.
Steps:
This is how I would construct it with some crude error handling:
$(document).ready(function() {
$.ajax({
url: "http://example.com/json",
type: 'POST',
dataType: 'jsonp',
timeout: 3000,
success: function(data) {
// Variables created from response
var userLocation = data.loc;
var userRegion = data.city;
// Using variables for another call
$.ajax({
url: "http://example2.com/json?Location=" + userLocation + "&City=" + userRegion,
type: 'POST',
dataType: 'json',
timeout: 3000,
success: function(Response) {
$(.target-div).html(Response.payload);
},
error: {
alert("Your second API call blew it.");
}
});
},
error: function () {
alert("Your first API call blew it.");
}
});
});
Now we are ready to build out a JavaScript application that will make an API call. There are many different ways to make an API call in JavaScript ranging from using vanilla JavaScript to jQuery to using other tools that vastly simplify making API calls.
In terms of architecture, you may consider using Promise pattern to decouple each step into one function, each function cares only about it's own task (do not reference to another step in the flow). This gives more flexibility when you need to reuse those steps. These individual step can be chained together later on to form a complete flow.
https://www.promisejs.org/patterns/
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/category/deferred-object/
function displayPayload(response) {
$(".target-div").html(response.payload);
}
function jsonpCall() {
return $.ajax({
url: "http://example.com/json",
type: 'GET',
dataType: 'jsonp',
timeout: 3000
});
}
function jsonCall(data) {
// Variables created from response
var userLocation = data.loc;
var userRegion = data.city;
// Using variables for another call
return $.ajax({
url: "http://example2.com/json?Location=" + userLocation + "&City=" + userRegion,
type: 'GET',
dataType: 'json',
timeout: 3000
});
}
$(document).ready(function() {
jsonpCall()
.done(function(data) {
jsonCall(data)
.done(function(response) {
displayPayload(response);
}).fail(function() {
alert("Your second API call blew it.");
});
}).fail(function() {
alert("Your first API call blew it.");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With