Reputation: 1032
I am stuck on attempting to validate my form data before I am able to perform and AJAX update. So basically what I am trying to achieve is validate the form input data before the ajax update function. I do not know where I would place the functions for validation inside the method below: My AJAX updating function:
$("#updateUser").click(function() {
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateUser",
data: $("#updateForm").serialize(),
success: function(response) {
$("#alert").show();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
This is the form I am attempting to validate:
<form id="updateForm">
<input type="hidden" id="id" name="id" />
Name:
<input type="text" name="name" id="name" />
<br />
User name:
<input type="text" name="username" id="username" />
<br />
Email:
<input type="text" name="email" id="email" />
<br />
Authority
<input type="text" name="authority" id="authority" />
<br />
</form>
Any suggestions please help, I am new to javascript. Thanks
Upvotes: 0
Views: 209
Reputation: 22619
If you are using jQuery validation you can do in below way
$("#updateUser").click(function() {
var form = $( "#updateForm" );
form.validate();
if(form.valid()){
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateUser",
data: $("#updateForm").serialize(),
success: function(response) {
$("#alert").show();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
});
Upvotes: 1
Reputation: 80
You should place your validation code before sending ajax call.
$("#updateUser").click(function() {
var allright = true;
if ($('#name').val() == ''){
allright = false;
highlight_input('#name');
}
if (allright){
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/updateUser",
data: $("#updateForm").serialize(),
success: function(response) {
$("#alert").show();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
});
Upvotes: 1