J.Zil
J.Zil

Reputation: 2449

Submit form only after API query was successful to populate field

I've got a form like this:

<h4>Front Page</h4>
<form action="/action_page.php" method="get">
  <input value="EC2R 6DA" id="postcode_input">
  <input id="admin_district" placeholder="Admin District">
  <input type="button" id="get_postcode" value="Check">
</form>

And JavaScript like this:

$(document).ready(function() {
  $("#get_postcode").click(function(event) {
    event.preventDefault();
    var postcode = $("#postcode_input").val();
    $.get(encodeURI("https://api.postcodes.io/postcodes/" + postcode))
      .done(function(data) {
        $("#admin_district").val(data.result['admin_district']);
        console.dir(data);
      })
      .fail(function(error) {
        fullResult.html(JSON.stringify(error.responseJSON, null, 4)).slideDown();
      });
  });
});

I'm wondering how I validate that the JavaScript API call completed before submitting the form, and then if it did, then I submit the form. At the moment it prevents the form from submitting so it can make the API call, but after the API call completed, it then doesn't do anything, when it should then submit the form.

Upvotes: 0

Views: 36

Answers (1)

jpmc
jpmc

Reputation: 1193

Give your form an id attribute

<form id="myForm" action="/action_page.php" method="get">

Then in your $.get, in the .done function add:

$("#myForm").submit()

Upvotes: 1

Related Questions