CodingerSK
CodingerSK

Reputation: 31

Need help understanding .getJSON() behavior

I'm trying to understand why the .getJSON() call throws an error when form submission is not suppressed. Initially I thought that maybe the form submission meant that the function wikiCall() is not being initiated. However, the correct "wikiLink" [wikiCall()'s argument] is printed in console when form is submitted on enter, yet this causes the .getJSON() to fail.

The HTML

<div class="text-center searchBar">
  <form action="">
    <input type="text" id="searchText" />
  </form>
</div>

<div class="container displayResults"> </div>

The Javascript:

$(document).ready(function() {
   $('#searchText').keypress(function(e) {
     var searchItem = $('#searchText').val();
     var link = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&exlimit=max&inprop=url&generator=search&gsroffset=&format=json&formatversion=2&callback=?&gsrsearch=' + searchItem;

     if(e.which == 13) { //if user returns enter key
      wikiCall(link);
      //e.preventDefault(); //.getJSON throws error if form submission is not suppressed
     }    
   });
});

function wikiCall(wikiLink) { 
  console.log(wikiLink); //prints the correct link even on form submit
  $.getJSON(wikiLink, function(searchResults) {      
    for (var i = 0; i < searchResults.query.pages.length; i++) {
      $(".displayResults").append("<div class='searchResultsContainer'><span style='font-weight:bold; font-size:150%; margin-bottom:100px;'>" + searchResults.query.pages[i].title + "</span><br></br>" + searchResults.query.pages[i].extract + "</div>");
      $(".displayResults").append("<br>");
    }
  }).fail(function(jqxhr,textStatus,error){
    alert(textStatus+": "+error); //shows error:error if form is submitted on enter
  });
}

Upvotes: 1

Views: 84

Answers (2)

Miguel Lattuada
Miguel Lattuada

Reputation: 5407

Why don't you just send the request on from submit.

$(document).ready(function() {
   $('form').on('submit', function(e) {
     e.preventDefault();
     var searchItem = $('#searchText').val();
     var link = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&exlimit=max&inprop=url&generator=search&gsroffset=&format=json&formatversion=2&callback=?&gsrsearch=' + searchItem;
      wikiCall(link);
   });
});

function wikiCall(wikiLink) { 
  console.log(wikiLink); //prints the correct link even on form submit

  //clean the div before append the new result;
  $(".displayResults").html('');

  $.getJSON(wikiLink, function(searchResults) {      
    for (var i = 0; i < searchResults.query.pages.length; i++) {
      $(".displayResults").append("<div class='searchResultsContainer'><span style='font-weight:bold; font-size:150%; margin-bottom:100px;'>" + searchResults.query.pages[i].title + "</span><br></br>" + searchResults.query.pages[i].extract + "</div>");
      $(".displayResults").append("<br>");
    }
  }).fail(function(jqxhr,textStatus,error){
    alert(textStatus+": "+error); //shows error:error if form is submitted on enter
  });
}

Here is a working example with your code and form submitting, just type and hit enter. http://jsbin.com/hexoyocusa/edit?html,js,output

Upvotes: 1

iMoses
iMoses

Reputation: 4348

Because the action attribute on your form element is an empty string, by submitting the form you are effectively refreshing the page, which causes the browser to abort all open Ajax requests, thus triggering the error handler just before leaving the page. Unless your console is preserving logs between pages, the error message should appear only for a short time before the next page is loaded.

Your code doesn't make much sense at the moment, you should always prevent the default behaviour of submitting a form if you do not wish to initiate the browser's navigation.

Upvotes: 1

Related Questions