I have an list displaying some information in a database, and when you add an item to the database I want the list to update.
function getList(id) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("list").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "tool/getlist.php?q=" + id);
xmlhttp.send();
}
function addItem() {
$.post('tool/addListItem.php', $("#addItem").serialize());
var listID = $("#addItem").serializeArray()[0].value;
getList(listID);
}
The information is add fine, the problem is that when I call the getList function from addItem(), nothing happens the first time if i call it again it updates, but then the third times nothing happens and on the forth it updates.
I ran some debugging with an alert before the update.
var listID = $("#addItem").serializeArray()[0].value;
alert(listID);
getList(listID);
If I do this it updates fine after I click ok.
I am still quite new to javascript and ajax in general, so it is possible that it is a simple mistake, but it has been driving me crazy for the past hours.
You are calling post and get is call before the post has done it job, i.e. putting data in database.
You need to call the getList in success of postso that you get the data from database. Read more about post here.