I have multiple dropdowns that each call the following function (passing different arguments)
If I change one dropdown and wait for the response everything is good.
If I change a second dropdown before the first response, It appears as if the first callback is never called. (the data is changed in the database though)
<script type="text/javascript">
<!--
function fg_insert_pick(element, team_id, tournament_id, pick_number) {
golfer_id = element.value;
golfer_name = element.options[element.selectedIndex].text;;
parent = element.parentNode;
parent.removeChild(element);
parent.innerHTML="submitting pick ...";
path = "'.plugins_url('fantasy-golf/submit/pick.php').'";
post = "team_id="+team_id+"&tournament_id="+tournament_id+"&pick_number="+pick_number+"&golfer_id="+golfer_id;
parent.innerHTML="submitting pick ...";
fg_ajax_request(path, post, function(response) {
if (response) {
parent.innerHTML=golfer_name;
} else {
parent.innerHTML="Something went wrong, please reload the page";
}
});
}
function fg_ajax_request(url, post, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange= function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(post);
}
//-->
</script>
This looks like a simple variable scope issue to me. The variables defined inside of your
fg_insert_pickare being set on the global level, not within the context of your function. So what you’re probably seeing is this:fg_insert_pickis called.golfer_nameis set to the element’s selected option andparentis set to the given element’s parent node.fg_insert_pickis called with a different element.golfer_nameandparentare then overwritten according to this element.fg_insert_pickis called. Sincegolfer_nameandparentlive outsidefg_insert_pick, they now refer to the second element, not the first. Hence, the second element is updated.tl;dr Add
vars to the variables set infg_insert_pick.