I am having trouble with ordering some Javascript AJAX interactions.
I have a form where a user enter's a gamertag (summonerName
). I then AJAX to the game's API to get that user's ID
.
However, if it is an invalid name (a GET error GET url 404 Not Found
) my JS events continue on before even waiting for the AJAX error
to finish.
So after the form submits I then get my notification saying an error occurred which is too late by then to halt the form.
I would have figured that the error
function would hold priority just like the success
function in that all my scripts should wait until it has finished.
var good = true; // if false will halt form when it reaches submission function
var summoner = $('#createSummonerName').val().trim();
var summonerID = "";
if (summoner != "" && summonerID == "") {
var ID = "";
ID = summoner;
var YOURKEY = "(key)";
alert("checking");
$.ajax({
url: 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + ID + '?api_key=' + YOURKEY,
type: 'GET',
dataType: 'json',
data: {
},
success: function (json) {
var userID = ID.replace(" ", "");
userID = userID.toLowerCase().trim();
summonerIDpull = json[userID].id;
summonerID = summonerIDpull;
alert("found");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
summonerID = "";
alert("not found");
document.getElementById("createSummonerName").className = document.getElementById("createSummonerName").className + " error";
good = false;
}
});
}
// more functions that validate and submit the form
So what happens is that the form will submit and the alert("not found");
occurs a second after that if a GET error occurs. :(
Is there anyway to get a error/issue/exception and make the script wait until that error has been processed? Because of the error's delay my good = false;
line does not run until after the form has been submitted which is bad.
I am still very new to AJAX so sorry if this is a simple answer and I am misunderstanding some concepts.