Onsubmit event using ajax and return true but Form not submit using Jquery
The onsubmit event is commonly used to validate the contents of form controls and set the contents of some input:hidden elements before submitting. If the user forgot to fill some required fields or made some other mistake on the form, you can cancel the submission with the onsubmit event. See the example below for details with ajax validation some field.
HTML Code
<form id="post-ad" method="post" action="saveAd1.php" enctype="multipart/form-data" onsubmit="return validateForm(this);">
<div class="form-group" id="dvBrandName" style="display: none;">
<label class="control-label">Brand Name<sup>*</sup></label>
<div class="input-box">
<input type="text" name="brand_name" id="brand_name" class="form-control" placeholder="">
<div id = "brandname_error" class="error_alertbox" style="display:none;"></div>
</div>
</div>
<div class="form-group" id="dvModel" style="display: none;">
<label class="control-label">Model</label>
<div class="input-box">
<input type="text" name="model" id="model" class="form-control" placeholder="">
<div id = "model_error" class="error_alertbox" style="display:none;"></div>
</div>
</div>
</form>
JavaScript / Jquery Code
function validateForm(form) {
var flag = 0;
var status = false;
var brandname = $('#brand_name').val();
if ($('#brand_name').val() == "") {
$('#cate_lbl').parent().addClass('err');
flag = 1;
var error_text = '<ul class="alert-list-error"> <li> Please select category.</li> </ul>';
$('#category_error').html(error_text);
$('#category_error').show();
}
if ($('#model').val() == '') {
$('#ad_title').addClass('err');
flag = 1;
var error_text = '<ul class="alert-list-error"> <li> Please add title to your ad.</li> </ul>';
$('#title_error').html(error_text);
$('#title_error').show();
}
if (flag == 1)
{
return status;
}
else
{
$.ajax({
type: "POST",
url: "checkbrandname.php",
global: false,
data: {brandname: brandname},
dataType: 'JSON',
async: false,
success: function(data) {
if(data.error)
{
$('#brand_name').addClass('err');
var error_text = '<ul class="alert-list-error"> <li> Captcha Code does not Match Please check.</li> </ul>';
$('#brandname_error').html(error_text);
$('#brandname_error').show();
status = false;
}
else if(data.success)
{
status = true;
}
}
});
return status;
}
}
Leave a Reply