I am in search of a solution that will allow an AJAX API call to finish before the containing function does without relying on jQuery as a dependency for just one REST call...
After going through multiple solutions, all of which involve using jQuery, I came across this question How do I return the response from an asynchronous call?. However, I am determined to find a way to achieve this without adding jQuery as a dependency.
Currently, when a failing zip code value is inputted and the user clicks Submit
, an alert pops up displaying other failed business rules but not the error related to "Mismatch in State and Zip."
). Upon console logging, it seems that the REST call is successfully made and a response is received, but the alert(error)
gets triggered before the async REST call completes and appends the value of error
.
JS
function checkForm(form){
var state = form.state;
var zip = form.zip;
var error = '';
var flag = 0;
var ckZip = checkZip(state, zip);
if (ckZip.flag == 1){
flag = 1;
}
error += ckZip.error;
// show error and disable form submit if flag == 1
if (flag == 1){
alert(error);
return false;
}
}
function checkZip(state, zip){
var state = form.state;
var zip = form.zip;
var error = '';
var flag = 0;
// check if value entered
if (zip == ''){
error += "Please provide a zip/postal code.\r\n";
flag = 1;
}
// business rule: cannot enter - in a ZIP
if (zip.search(/\x2d/) != -1){
error += "Please remove dash from zip or postal code.\r\n";
flag = 1;
}
// check if state and zip match
// IMPORTANT: Fill in your client key
var clientKey = "this-is-a-valid-key";
var zipcode = zip.substring(0, 5);
var url = "https://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
// Make AJAX request
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {alert("Got it");
// Success!
var data = JSON.parse(this.responseText);alert(data.state);
if (data.state != state){
error += "Mismatch in State and Zip.\r\n";
flag = 1;
}
} else {
// Error :(
var response = JSON.parse(this.responseText);
error += "error: " + response.error_msg;
}
}
};
request.send();
request = null;
return {flag: flag, error: error};
}
HTML
<form>
<select id="state" name="state">
<option value="" selected=""></option>
<option value="AA">APO AA</option>
<option value="AE">APO AE</option>
<option value="AP">APO AP</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<!-- ... -->
</select>
<input type="text" id="zip" name="zip" value="">
<input type="Submit" id="Submit" name="Submit" value="Continue" onclick="return checkForm(this.form)">
</form>