I\'m making a comment feature for my website and need to make it so that after the person submits a comment (and it contains errors), it will show the error without refreshi
I think it is easier to do the validation at the client side via Javascript. Instead of simply using a button of type submit
, write a function and bind it to the button's onclick()
event.
Something like this:
function submit() {
if (document.getElementById("myTextarea").value=='') {
alert("Your comment is too short.");
}
else {
document.getElementById("myForm").submit();
}
}
For basic validations like empty fields or length of input box you can use jQuery validate plugin -- http://jquery.bassistance.de/validate/demo/ or write something of your own.
You can use jQuery for a better AJAX/error handling. Check the documentation for jQuery AJAX here -- http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html", //URL to send the request
success: function() {
//do something. This is fired when your response is successful
},
error: function() {
//highlight the field that has error or do something else here.
}
);
Hope this helps :)
Use Javascript
HTML:
<button name="reply_submit" class="btn post-button" onclick="validate()">Post comment</button>
Javascript:
<script>
function validate(){
reply = document.getElementById('new_reply').value;
if (reply==null || reply=="")
{
alert("Your comment is too short.");
return false;
}
}
</script>