I have written the following jQuery for autorefreshing a page containing a poll (to keep updating the current winning option)
function update() {
var vote_radio = $('input:radio[name=vote_radio]:checked').val();
$.ajax({
type: 'POST',
url: 'index.php',
data: 'refresh=true&maintain_radio='+ vote_radio,
timeout: 2000,
success: function(data) {
$("#current_body").html(data);
$("#notice_div").html('');
$("[name=vote_radio]").filter("[value="+vote_radio+"]").attr("checked","checked");
window.setTimeout(update, 2000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
};
$(document).ready(update);
There is a radiobutton poll on the page named “vote_radio”, I also use the following code with that, to Ajax the answers to the server:
$(function() {
$('.error').hide();
$('.failure').hide();
$('.success').hide();
$(".vote_submit").click(function() {
if (!$("input[@name='name']:checked").val()) {
$('.error').show();
return false;
}
var vote_radio = $('input:radio[name=vote_radio]:checked').val();;
var dataString = 'vote_radio='+ vote_radio;
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
success: function() {
$('.success').show();
$('.failure').hide();
},
error: function() {
$('.failure').show();
$('.success').hide();
}
});
return false;
});
});
The problem I’m having with all this is that if a user selects their option WHILE the page is auto-refreshing it puts the selected radio option back to how it was WHEN the page started auto-refreshing, which is frustrating.
Also, if the .success class has been told to appear by the second script, when the first script autorefreshes the page it hides the success class again.
Why are you reverting the
vote_radioelement back to the value before initiating the AJAX call ?Just read it right before overwriting it, so you keep the current value (even if it changed without being submitted yet)
so just change the success callback to
But, in general, the correct way would be to update only the parts of the page that need updating, and not the whole page.. that is the whole point of AJAX..