I need an AJAX API call to complete before it's containing function does. All the solutions I have looked up use jQuery, which I do not want to add as a dependency just to make a single REST call...
I have been reading the following question How do I return the response from an asynchronous call? and am still attempting to make it work. Again, I do not want to add jQuery as a dependency.
Right now if a failing zip code value is entered, when the user clicks Submit
an alert will show the other failing business rules without the "Mismatch in State and Zip."
error. When logging to console I see that the REST call is made and a successful response received, but it appears alert(error)
is called before the async REST call has completed and appended 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>