Error in submitting form using ajax - javascript

For some reason, the form is not getting submitted. I have used ajax form to save the form details in my database.
Here is the site link:
http://www.famproperties.com/mudon/Abu-Dhabi/villas.html
Here is the script code.
<script>
$(document).ready(function() {
$("#submit-form-button").click(function() { submitForm(); });
});
function submitForm() {
if ( $("#NAME").val() == '' ||
$("#EMAIL").val() == '' ||
$("#MOBILE").val() == '' ||
$("#NOTE").val() == '' )
{ alert ("All field are required");}
else {
$.ajax({
type: "POST",
url: "http://famproperties.com/real_estate/property/contact/lead/",
data: {
NAME: $("#NAME").val(),
EMAIL: $("#EMAIL").val(),
MOBILE: $("#MOBILE").val(),
NOTE: $("#NOTE").val(),
SOURCE: 'MSB.COM'
},
success: function() {
alert("Thanks, Our specialist will contact you soon.");
},
dataType: 'html'
});
$("#NAME").val('');
$("#EMAIL").val('');
$("#MOBILE").val('');
$("#NOTE").val('');
}};
</script>
Here is the form code.
<!--NEW FORM -->
<div class="form-horizontal" role="form" accept-charset="UTF-8" action="http://famproperties.com/real_estate/property/contact/lead/" autocomplete="on" id="pro-form" method="post">
<div class="form-group">
<label for="NAME" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="NAME" required="" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="EMAIL" class="col-sm-2 control-label ">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="EMAIL" required="" placeholder="me#example.com">
</div>
</div>
<div class="form-group">
<label for="MOBILE" class="col-sm-2 control-label">Mobile</label>
<div class="col-sm-10">
<input type="phone" class="form-control inputs" id="MOBILE" required="" placeholder="Mobile">
</div>
</div>
<div class="form-group">
<label for="NOTE" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="NOTE" required="" placeholder="Note">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<a href="#" onclick="return false" class="btn btn-default btn-lg button" id="submit-form-button" style="background-color: #ffc600;
color: #2a292a;
width: 100%;"> Submit <span class="fa fa-chevron-right fa-1x"></span><span class="fa fa-chevron-right fa-1x"></span> </a>
</div>
</div>
</div>
<!--NEW FORM-->

Seeing the page on http://www.famproperties.com/mudon/Abu-Dhabi/villas.html you are not even loading jquery check the console and youll see this error:
Uncaught ReferenceError: $ is not defined
Thats why ajax is not working
Edit: Sorry, checking your code again i saw you are loading jQuery but you are trying to use jQuery before loading it. So, try moving the jquery script tag to the header or move your js below the jQuery script tag.

Related

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

Disabling and enabling button through jQuery but onclick event not trigerred after button enabled

I have a problem which I dont seem to find a solution for. The problem is this: I have some jQuery which will keep the button disabled until all the form's fields are filled up. When all the fields are filled up the button is being enabled, but the javascript onSubmit event used for the google recaptcha is not being trigerred. Anyone can help in this, please
Code is the one below:
//jquery to disable button until all fields are filled up
$().ready(function() {
// validate signup form on keyup and submit
$("#fbForm").validate({
rules: {
name: {
required: true
},
surname: {
required: true
},
terms: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#fbForm').change(function() {
if ($("#fbForm").valid()) {
$("#btnSubmit").removeAttr("disabled");
}
});
//recaptcha JS
function onSubmit(token) {
if (screen.width >= 768) {
document.getElementById("fbForm").submit();
}else if (screen.width <= 767){
document.getElementById("fbForm2").submit();
}
}
<form id="fbForm"class="well form-horizontal" action="winesOfDistinction.php?send=true" method="post" data-toggle="validator">
<div class="form-group">
<label for="name "class="col-md-4 control-label">First Name</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="First Name" name="name" id="name" class="form-control" data-minlength="2" data-error="Minimum Lenght of First Name must be made up of at least 2 characters!" value="<?= $name ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<!-- Surname: Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="surname">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="Last Name" name="surname" id="surname" class="form-control" data-minlength="2" data-error="Minimum Lenght of Last Name must be made up of at least 2 characters!" value="<?= $surname ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group text-center">
<div class="checkbox">
<label>
<input type="checkbox" name="terms"id="terms" data-error="Please check the GDPR Disclaimercheck box in order to be able to submit the data" required>
I agree
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4"><br>
<button id="btnSubmit" name="btnSubmit" disabled="disabled" type="submit" value="" class="g-recaptcha btn btn-success" data-sitekey="6LfuAWcUAAAAAEKjLeOZfygAMxAeld1k4UUMGnfN" data-callback='onSubmit'>SUBMIT <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
You are missing a } at the last line to close the ready function. Fix that first.
$().ready(function() {
$('#num').validate();
// validate signup form on keyup and submit
$("fbForm").validate({
rules: {
name: {
required: true
},
surname: {
required: true
},
terms: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#fbForm').change(function() {
if ($("#fbForm").valid()) {
$("#btnSubmit").removeAttr("disabled");
}
});
//recaptcha JS
function onSubmit(token) {
if (screen.width >= 768) {
document.getElementById("fbForm").submit();
}else if (screen.width <= 767){
document.getElementById("fbForm2").submit();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<form name="formSend" id="fbForm" class="well form-horizontal" action="winesOfDistinction.php?send=true" method="post" data-toggle="validator">
<fieldset>
<div class="form-group">
<label for="name "class="col-md-4 control-label">First Name</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="First Name" name="name" id="name" class="form-control" data-minlength="2" data-error="Minimum Lenght of First Name must be made up of at least 2 characters!" value="<?= $name ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<!-- Surname: Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="surname">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="Last Name" name="surname" id="surname" class="form-control" data-minlength="2" data-error="Minimum Lenght of Last Name must be made up of at least 2 characters!" value="<?= $surname ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group text-center">
<div class="checkbox">
<label>
<input type="checkbox" name="terms"id="terms" data-error="Please check the GDPR Disclaimercheck box in order to be able to submit the data" required>
I agree
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4"><br>
<button id="btnSubmit" name="btnSubmit" disabled="disabled" type="submit" value="" class="g-recaptcha btn btn-success" data-sitekey="6LfuAWcUAAAAAEKjLeOZfygAMxAeld1k4UUMGnfN" data-callback='onSubmit'>SUBMIT <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
Okay, Missing jquery validtor and syntax errors were causing the problem. The snippet works fine.You should use visual code as editor and please resolve syntax errors before posting here.

Why is preventDefault not working?

Here is my javascript code. The commented line works:
$("#regForm").submit(function(event) {
// event.preventDefault()
password = $("#inputPassword3")
login = $("#inputEmail3")
user_instance = 0
$.ajax({
url: "{{ url_for('get_users') }}",
method: 'POST'
}).done(function(data) {
data.forEach(function(item) {
if (item.username == login.val() || item.mail == login.val()) {
user_instance = item
}
})
pass_arr = sjcl.hash.sha256.hash(password.val())
hash = sjcl.codec.hex.fromBits(pass_arr)
console.log(hash, user_instance.passwd)
if (hash != user_instance.passwd) {
event.preventDefault()
console.log("+")
password.attr("style", "border:#f00 solid 1px")
password.attr("placeholder", "Wrong password")
}
event.preventDefault() is not working here:
<div id="regForm">
<form class="form-horizontal" method="POST" action="{{ url_for('login') }}">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email/Login</label>
<div class="col-sm-10">
<input type="imput" class="form-control" id="inputEmail3" placeholder="Email/Login" name="email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" placeholder="Password" name="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="sign-in">Sign in</button>
</div>
</div>
</form>
It submits form anyway, even though color of form changing, why is that? When uncommented preventDefault() is working as should be
Try this
$('body').on('submit', 'YOUR-ID' ,function(event) {}

contact us web page using Ajax and php

I would like to create contact us web page without refreshing the page when click send button. My code bellow, but there are some problems:
1- The page is refreshed after submitting the form.
2- The value of the Contact form inputs appear in the URL after submitting the form. check this image
3- The confirmation message appears for 0.25 seconds then disappear or does not appear.
4- The email is not received to my email address when I use Firefox browser.
Please help me to solve those problems.
HTML
<div class="col-sm-8 col-sm-offset-2" id="mail-status">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-8 col-xs-12 col-sm-offset-2">
<div class="well">
<form class="form-horizontal">
<fieldset>
<legend class="legend-title">I'd <span class="heart"><i class="fa fa-heart"></i></span> to contact you!</legend>
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="name" placeholder="Name" required="required">
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" required="required">
</div>
</div>
<div class="form-group">
<label for="inputSubject" class="col-sm-2 control-label">Subject</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputSubject" name="subject" placeholder="Subject" required="required">
</div>
</div>
<div class="form-group">
<label for="textAreaMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-9">
<textarea class="form-control" rows="5" id="textAreaMessage" name="message" placeholder="Message" required="required" minlength=5 ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-8">
<button type="submit" class="btn btn-primary right-button" id="send" onClick="sendContact()">Send</button>
</div>
</div>
</fieldset>
</form>
Javascript
function sendContact() {
jQuery.ajax({
url: "send_email.php",
data:'inputName='+$("#inputName").val()+'&inputEmail='+$("#inputEmail").val()+'&inputSubject='+$("#inputSubject").val()+'&textAreaMessage='+$(textAreaMessage).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
php
<?php
$toEmail = "*****#***.com";
$mailHeaders = "From: " . $_POST["inputName"] . "<". $_POST["inputEmail"] .">\r\n";
if(mail($toEmail, $_POST["inputSubject"], $_POST["textAreaMessage"], $mailHeaders)) {
print "<div class='alert alert-success'> <button type='button' class='close' data-dismiss='alert'>×</button> Thank you for your email! I will be in touch.</div>";
} else {
print "<div class='alert alert-danger'> <button type='button' class='close' data-dismiss='alert'>×</button> We are sorry, but there is a problem. Please Make sure all fields are filled!</div>";
}
?>`
Get rid of the inline onclick() event in your HTML, and let your JavaScript handle the click:
$('#send').click(function(e){
e.preventDefault();
sendContact();
});
preventDefault() stops the click event from acting normally, so your form data is submitted without reloading the page.

Issue with jQuery validate not working against element

I am having an issue using jQuery validate against a form in a current project.
I am sure it is a typo I am missing or something small, but can't sem to figure out why it is occurring.
The error I am getting in the console debugger is: Object doesn't support property or method 'validate'
The bundle configuration file:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Scripts/ContactForm.js"));
The code snippets are below:
<form action="#Url.Action("UpdateContactInformation", "ContactController")" method="post" role="form" class="form-horizontal" id="contactForm">
<input type='hidden' name='csrfmiddlewaretoken' value='brGfMU16YyyG2QEcpLqhb3Zh8AvkYkJt' />
<!-- First Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">First Name</label>
<div class="col-md-4">
<input class="form-control" id="id_firstName" maxlength="75" name="txtFirstName" placeholder="First Name" required="required" title="" type="text" />
</div>
</div>
<!-- Last Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Last Name</label>
<div class="col-md-4">
<input class="form-control" id="id_lastName" maxlength="75" name="txtlastName" placeholder="Last Name" required="required" title="" type="text" />
</div>
</div>
<!-- Title Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Title</label>
<div class="col-md-4">
<input class="form-control" id="id_title" maxlength="75" name="txtTitle" placeholder="Title" required="required" title="" type="text" />
</div>
</div>
<!-- Address Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Address</label>
<div class="col-md-4">
<input class="form-control" id="id_address" maxlength="75" name="txtAddress" placeholder="Address" required="required" title="" type="text" />
</div>
</div>
<!-- City Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">City</label>
<div class="col-md-4">
<input class="form-control" id="id_city" maxlength="75" name="txtCity" placeholder="City" required="required" title="" type="text" />
</div>
</div>
<!-- State Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">State</label>
<div class="col-md-4">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuStates" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Select State
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="statesDropDownMenu" aria-labelledby="dropdownMenuStates">
</ul>
</div>
</div>
</div>
<!-- Zip Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">ZipCode</label>
<div class="col-md-4">
<input class="form-control" id="id_zipCode" maxlength="75" name="txtZipCode" placeholder="ZipCode" required="required" title="" type="number" />
</div>
</div>
<!-- Email Primary Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Email Primary</label>
<div class="col-md-4">
<input class="form-control customEmail" id="id_emailPrimary" maxlength="75" name="txtEmailPrimay" placeholder="Email Primary" required="required" />
</div>
</div>
<!-- Email Secondary (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailSecond" maxlength="75" name="txtEmailSecond" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<!-- Email Third (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailThird" maxlength="75" name="txtEmailThird" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-user"></span> Submit Contact Info
</button>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval");
#Scripts.Render("~/bundles/custom"); //contains the file I am trying to add $.validate.AddMethod() to
Here is the code for Contact.js
$.validator.addMethod(
"customEmail",
function (value, element) {
var re = new RegExp("/^#{0,2}\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*#{0,2}​‌‌​​$/");
return this.optional(element) || re.test(value);
},
"Please enter a valid email address."
);
$(document).ready(function () {
console.log("Were here.........");
// populateStatesDropDown();
$('#contactForm').validate({ // initialize the plugin
rules: {
txtZipCode: {
required: true,
numeric: true
},
txtEmailPrimay: {
required: true,
customEmail:true
},
txtEmailSecond:{
required:false,
customEmail:true,
},
txtEmailThird: {
required: false,
customEmail:true
}
}
});
populateStatesList();
});
function populateStatesList() {
var url = "Contact/GetStates"; // Don't hard code your url's!
//$("#province_dll").change(function () {
var $statesDropDownMenu = $("#statesDropDownMenu"); // Use $(this) so you don't traverse the DOM again
var listItems = '';
$.getJSON(url, function (response) {
$statesDropDownMenu.empty(); // remove any existing options
console.log(response);
$.each(response, function (index, item) {
console.log("Now - " + item);
listItems += "<li>" + item + "</li>";
});
$statesDropDownMenu.html(listItems);
});
//});
}
You have an extra comma.
txtEmailSecond:{
required:false,
customEmail:true, // Here
},

Categories

Resources