Last active
August 3, 2018 10:24
-
-
Save jcamp/8cc01ae9b7cb577abbe36d4fa058366c to your computer and use it in GitHub Desktop.
Use Ajax to check form fields and submit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var isHttps = location.protocol.match(/https/); | |
var http = isHttps ? 'https://' : 'http://'; | |
var site_url = http + location.host + '/yoursite'; | |
$(function(){ | |
$('#form-btn').on('click',function(event){ | |
var email_test = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
var form_name = $('#form-name').val(); | |
var form_email = $('#form-email').val(); | |
var form_contact = $('#form-contact').val(); | |
var form_message = $('#form-message').val(); | |
var page = $('#page-category').data("category-value"); | |
if(form_name == "" || form_email == "" || form_contact == "" || form_message == "") { | |
$('#form-notification').html('<div class="alert alert-danger form-msg text-center">Please complete all the fields</div>').hide().fadeIn(); | |
var error = 1; | |
$('.form-group').each(function(){ | |
var field = $(this).find('.form-field'); | |
if(field.val() == ""){ | |
field.addClass('error-field'); | |
} else { | |
field.removeClass('error-field'); | |
} | |
}); | |
} else if( !email_test.test(form_email) ){ | |
$('#form-notification').html('<div class="alert alert-danger form-msg text-center">Invalid E-mail Address</div>').hide().fadeIn(); | |
var error = 1; | |
} else if( form_contact.length < 10 ) { | |
$('#form-notification').html('<div class="alert alert-danger form-msg text-center">Contact No. must be greater than 10 digits</div>').hide().fadeIn(); | |
var error = 1; | |
} | |
if( error == 1 ){ | |
console.log('error'); | |
} else { | |
var formdata = { | |
form_name : form_name, | |
form_email : form_email, | |
form_contact : form_contact, | |
form_message : form_message, | |
page : page | |
}; | |
$.ajax({ | |
data : formdata, | |
type : 'POST', | |
dataType : 'JSON', | |
url : site_url + '/ajax-forms.php', | |
success: function(response){ | |
$('#cf-notification').html(response.notification).hide().fadeIn(); | |
if(response.status == 'success') { | |
//$('#form-notification').html(response.notification).hide().fadeIn().delay(12000).fadeOut('slow'); | |
//$('.form-field').val(''); | |
//$('.form-field').removeClass('error-field'); | |
window.location.href = "/thank-you/"; | |
} | |
return false; | |
}, | |
error: function(){ | |
console.log('error'); | |
} | |
}); | |
$('.form-field').removeClass('error-field'); | |
} | |
event.preventDefault(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment