Lewis
Lewis

Reputation: 2188

Ajax response won't print into target element?

I've been messing around with postcodes.io to build a simple form that searches the users postcode data. I can query postcodes.io just fine and get a response which, you can see in the console log. But for whatever reason I can't seem to get the response to print into the target element, in my case $('.ajaxResponse').html(response);

I'm stumped on this one, any help would be wildly appreciated.

$(document).ready(function() {
  $('#ajaxSubmit').click(function() {
    $.ajax({
      type: "get",
      url: 'https://api.postcodes.io/postcodes/' + $('#userPostCode').val(),
      dataType: 'json',
      success: function(response) {
        console.log(response); // Returns data;
        console.log($('.ajaxResponse')); // Is descoverable
        $('.ajaxResponse').html(response); // Not working ?
      },
      error: function(xhr, ajaxOptions, thrownError) {
        var msg = '';
        if (xhr.status === 0) {
          msg = 'Not connect.\n Verify Network.';
        } else if (xhr.status == 404) {
          msg = 'Requested page not found. [404]';
        } else if (xhr.status == 500) {
          msg = 'Internal Server Error [500].';
        } else if (thrownError === 'parsererror') {
          msg = 'Requested JSON parse failed.';
        } else if (thrownError === 'timeout') {
          msg = 'Time out error.';
        } else if (thrownError === 'abort') {
          msg = 'Ajax request aborted.';
        } else {
          msg = 'Uncaught Error.\n' + xhr.responseText;
        }
      }
    });
  });
  $('#ajaxSubmit').submit(function(e) {
    e.preventDefault();
  });
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <div class="jumbotron">
    <h1>Search Postcodes.io</h1>

    <form method="get" action="">
      <div class="form-row align-items-center mb-3">
        <div class="col-auto">
          <label class="sr-only" for="userPostCode">Postcode</label>
          <input type="text" name="postcode" class="form-control form-control-lg mb-2" id="userPostCode" placeholder="AL1 2BQ" required>
        </div>
        <div class="col-auto">
          <button type="button" id="ajaxSubmit" class="btn btn-lg btn-primary mb-2">Submit</button>
        </div>
      </div>
    </form>
    
    <p>The response:</p>
    <div class="ajaxResponse"></div>

</div>

Upvotes: 1

Views: 42

Answers (1)

Richard Lovell
Richard Lovell

Reputation: 888

If it's a JSON object, perhaps you need to stringify it. Could you try: $('.ajaxResponse').text(JSON.stringify(response));

Upvotes: 2

Related Questions