EDIT: My question is not a duplicate of No response from MediaWiki API using jQuery. Because even though it's a cross-domain request, I'm properly triggering JSONP behavior because jquery is automatically sending a callback parameter under the hood. (As you can see from the link I posted jQuery3100048749602337837095_1485851882249&_=1485851882253
EDIT2: Solved by @AnandMArora. Solution:
<input type="submit" onclick="getUserInput(event)" style="display:none"/>
and function
getUserInput(evt) { evt.preventDefault();
But since it's a comment I can't mark it as the answer. If there's an explanation why this method works (what is the default behavior that is prevented etc.) I will select it as the answer.
I assume that the "alert" method is buying time for the AJAX function since it's asynchronous. But I have no idea WHY do I need to buy time here. It should only be executed when getUserInput()
calls getWiki()
with the Input
parameter.
In fact, I looked at the network monitor and even if we remove alert("")
the proper URL is called (assuming "batman" was submitted).
If I open this link manually, it works fine. But there's no status code returned and console logs "Error!"
function getUserInput(){
var Input = document.getElementById("searchBox").value;
getWiki(Input);
alert(""); //If we remove this line the request fails
}
function generatePage(rawData) {
console.log(rawData);
var mainData = rawData.query.pages;
$.each(mainData, function(value){
console.log((mainData[value].title + " " + mainData[value].extract));
});
}
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
dataType: "JSONP",
type: "GET",
success: function (rawData) {
generatePage(rawData);
},
error: function() {
console.log("Error!")
}
});
}
$(document).ready(function(){
})
The html I'm using to submit is:
<form class="searchForm">
<input type="text" name="searchRequest" id="searchBox" >
<input type="submit" onclick="getUserInput()" style="display:none"/>
</input>
</form>
My questions would be:
1) Why is this happening?
2) How can this be fixed without turning async
off or using setTimeout()
on the ajax function?