Manuca Manuca - 4 years ago 89
jQuery Question

JQuery form submission not working with API

I am trying to retrieve date from a form submission to use in a SmartyStreet API request. It's not outputting the response from the API.

HTML:

<div class="form-style-5">
<form id="myForm">
<fieldset>
<legend><span class="number">1</span> Input Address</legend>
<input type="text" id="street" name="street" placeholder="Street">
<input type="text" id="city" name="city" placeholder="City">
<input type="text" id="state" name="state" placeholder="State">
<input type="submit" value="Submit" />
</fieldset>
</form>
<fieldset>
<legend><span class="number">2</span> Results</legend>
<div id='resultBox'>
</div>
</fieldset>
</div>


JS:

AUTH_ID = "123456789";
AUTH_TOKEN = "123456789"

$("myForm").submit(function(event) {
street = $("#street").val()
city = $("#city").val()
state = $("#state").val()

var xhr = new XMLHttpRequest();
xhr.open("get", "https://us-street.api.smartystreets.com/street-address?street=" + street + "&auth-id=" + AUTH_ID + "&auth-token=" + AUTH_TOKEN, true);
xhr.send();
var addresses = JSON.parse(xhr.responseText);
console.log('Hello')

$( "#resultBox" ).text(addresses).show();
event.preventDefault();
});


Any help is appreciated, I just want to know why it isn't working and if there is a better way. Thanks

Answer Source

You can use the onreadystatechange property to monitor the state of your request,when the state changes the function gets called, when the status of the request is 4 (Completed) and Response status code is 200 (OK), then you change the address text using the returned json data from the response text property. I hope this helps.

$("myForm").submit(function(event) {
    event.preventDefault();
    street = $("#street").val()
    city = $("#city").val()
    state = $("#state").val()

    var xhr = new XMLHttpRequest();
    xhr.open("get", "https://us-street.api.smartystreets.com/street-address?street=" + street + "&auth-id=" + AUTH_ID + "&auth-token=" + AUTH_TOKEN, true);
    xhr.send();
    var addresses;

    xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == 4 && xhr.status == 200) {
      addresses = JSON.parse(xhr.responseText);
      $( "#resultBox" ).text(addresses).show();
      console.log('Hello');
      }
    }
 });     
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download