1

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
  });
}
CodingerSK
  • 31
  • 4
  • 3
    Well, if the form is submitted the page reloads, and the ajax call probably succeeds, but anything appended into the DOM will be lost when the page reloads, and to be clear, again, the page reloads. – adeneo Jan 21 '16 at 20:57
  • Possible duplicate of [handle ajax error when a user clicks refresh](http://stackoverflow.com/questions/699941/handle-ajax-error-when-a-user-clicks-refresh) – showdev Jan 21 '16 at 20:57
  • works fine here http://jsfiddle.net/oyu0qzmb/ Should empty the container for each new request though – charlietfl Jan 21 '16 at 21:02
  • Probably the request is aborted, this is what i would expect – A. Wolff Jan 21 '16 at 21:14
  • 1
    The code in the question should be the code you're actually asking about. The code you posted **does** suppress form submission. – Barmar Jan 21 '16 at 21:22
  • 1
    If you check your network tab, you can see the request is aborted, this is expected behaviour – A. Wolff Jan 21 '16 at 21:31
  • @Barmar I apologize, you are right. I should have commented out the e.preventDefault() to force the .fail() I have edited the code to reflect this. – CodingerSK Jan 22 '16 at 00:12
  • @charlietfl seems to indeed work fine on jsfiddle but will fail on codepen or jsbin – CodingerSK Jan 22 '16 at 01:35
  • provide link to demo where it fails. I suspect you aren't using `document.ready` that fiddle does automatically – charlietfl Jan 22 '16 at 01:38
  • http://jsbin.com/xewedereni/1/edit?html,js,output – CodingerSK Jan 22 '16 at 02:03

2 Answers2

1

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

Miguel Lattuada
  • 5,327
  • 4
  • 31
  • 44
1

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.

iMoses
  • 4,338
  • 1
  • 24
  • 39