When I click on the submit button, it still submits the form without validating the fields. I looked on other solutions here too, but no question mentions about what to do in the click function on submit.
Here's my code: https://jsfiddle.net/ishtiaq156/an1xqoxz/
Form:
$('#submitContact').click(function() {
var customerId = $('#customerId').val();
var formData = $('#addCustomerForm').serialize();
$.ajax({
url: "/abc/admin/customer/" + customerId + "/addContact",
type: "POST",
dataType: "json",
data: formData,
success: function(data) {
location.reload();
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
JavaScript:
$('#submitContact').click(function() {
var customerId = $('#customerId').val();
var formData = $('#addCustomerForm').serialize();
$.ajax({
url: "/abc/admin/customer/" + customerId + "/addContact",
type: "POST",
dataType: "json",
data: formData,
success: function(data) {
location.reload();
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
One way I've done it in the past is adding a submit handler to the validation code which calls your ajax function. Then you can change your button to type="submit"
$('#addCustomerForm').validate({
rules: {
/* removed for brevity */
},
messages: {
/* removed for brevity */
},
submitHandler: function (form) {
updateRecord();
/* $("#dialog-form").dialog("close"); - if using dialog */
}
/* ....add other options as needed */
});
function updateRecord() {
var customerId = $('#customerId').val();
var formData = $('#addCustomerForm').serialize();
$.ajax({
url: "/abc/admin/customer/" + customerId + "/addContact",
type: "POST",
dataType: "json",
data: formData,
success: function(data) {
location.reload();
},
failure: function(errMsg) {
alert(errMsg);
}
});
}
Also, you can send all your form variables using data rather than adding some to the URL:
data: {
customerId: customerId,
addContact: "addContact",
...add other form fields
}