I'm using Ajax for my comments form, but I can only get the script to run once without reloading the page.
Here's the form:
Code:
<form method="post" action="javascript:postComment('<?php echo $usrFieldName; ?>','<?php echo $bdyFieldName; ?>')">
<fieldset>
<input type="text" name="<?php echo $usrFieldName; ?>" id="<?php echo $usrFieldName; ?>" />
<textarea name="<?php echo $bdyFieldName; ?>" id="<?php echo $bdyFieldName; ?>" rows="5" cols="15"></textarea>
<input type="submit" name="submit" id="submit" value="Post Your Comment" />
</fieldset>
<fieldset id="status">
</fieldset>
</form>
In order to prevent spam I randomly generate the field names using a technique I found, so I pass the names to my Ajax script.
The script looks like this:
Code:
function postComment(usrFieldName,bdyFieldName) {
// get field values
var cUsername = escape(document.getElementById(usrFieldName).value);
var cBody = escape(document.getElementById(bdyFieldName).value);
// disable submit button and display status message
$('#submit').attr('disabled',true);
$('#status').html('Please Wait');
if (window.XMLHttpRequest) {
comment=new XMLHttpRequest();
}
else if (window.ActiveXObject) {
comment=new ActiveXObject("Microsoft.XMLHTTP");
}
if (comment==null) {
$('#status').html('<strong>Error:</strong> Your browser does not support this script');
return;
}
comment.open('POST', 'comment-handler.php', true);
comment.setRequestHeader('Content-type','application/x-www-form-urlencoded');
comment.onreadystatechange = function() {
if (comment.readyState == 4 && comment.status==200) {
// if there are no errors on the comment handler page . . .
if (comment.responseText == "comment posted")
$('#status').html('Comment Posted').delay(1000).fadeOut(400);
// otherwise, echo the error list
else {
$('#status').html(comment.responseText);
$('#submit').attr('disabled',false);
}
}
}
comment.send(usrFieldName+"="+cUsername+"&"+bdyFieldName+"="+cBody);
}
When I submit the form once it works perfectly, but any subsequent attempts without reloading the page produce no result at all.
If there aren't any errors I just hide the form anyway (to prevent spam), but if there's an error (required field left empty, for instance), I want the user to be able to fix his/her mistake and resubmit without having to reload the page.
|