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
});
}