Ajax ready/notready button without refresh
I am pretty much new to coding but i am learning along the way. i managed to make my buttons in php etcetera but ofcource this refreshes the page which made it very annoying.
I looked around and came to know Ajax. i managed to get certain page parts to auto refresh it's data and i also managed to make a button that changes it's test from Ready / Not Ready and sending data to a php file that processes it and updates the database.
However i am facing with one problem. for example, if a user uses the button sometimes and the database value is set to Ready. if they refresh the page. or close and come back the button would say it's default value Ready while the database already has it set Ready.
The eventual goal is that a user can set his status to ready or not ready for a game match. where the database gets updated so that info can be shown to other users.
I will post my code below, sorry if the code is a mess i can understand it very well might be since i took the pieces from examples on the internet.
var xmlHttp_five = AJAX();
function ajaxFunction(pid) {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlHttp_five) {
var txtname = document.getElementById("txtname");
xmlHttp_five.open("POST","includes/ga开发者_JS百科ther_buttons.php",true); //calling testing.php using POST method
xmlHttp_five.onreadystatechange = handleServerResponse;
xmlHttp_five.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp_five.send("txtname=" + txtname.value + "&pid=" + pid); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlHttp_five.readyState == 4) {
if(xmlHttp_five.status == 200) {
if (document.myForm.button1.value == "Ready") {
document.myForm.button1.value = "Not Ready";
document.myForm.txtname.value = "Waiting";
} else {
document.myForm.button1.value = "Ready";
document.myForm.txtname.value = "Ready";
}
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
and the form below
<form name='myForm'>
<input type='hidden' name='txtname' id='txtname' value='Ready'/>
<input type='button' class='button2' id='button1' value='Ready' onclick='ajaxFunction($pid);' />
</form>
If i need to give more info please say so, sorry if i am not supposed to post this here.
Thank you in advance.
Best regards,
Johan
Your form should be generated by server-side script. So when user refreshes page, he gets actual data from the database.
Otherwise if you can't generate form by server-side script, you should use preloader: button's value initially should be "loading..." and script should request the value by Ajax.
精彩评论