ajax form is not working how it should - javascript

hello i been working on a form using ajax but when it comes down to validating a select box
problem 1) every time i leave the job_est value empty the form is still submitted as if it was validated
problem 2) can i use async in ajax
sorry for my writing skills
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var l_name = $('input[name=l_name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var postcode = $('input[name=postcode]');
var house_number = $('input[name=house_number]');
var street = $('input[name=street]');
var job_est = $('select[name=job_est]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (l_name.val()=='') {
l_name.addClass('hightlight');
return false;
} else l_name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (postcode.val()=='') {
postcode.addClass('hightlight');
return false;
} else postcode.removeClass('hightlight');
if (house_number.val()=='') {
house_number.addClass('hightlight');
return false;
} else house_number.removeClass('hightlight');
if (street.val()=='') {
street.addClass('hightlight');
return false;
} else street.removeClass('hightlight');
if (job_est.val()=='') {
job_est.addClass('hightlight');
return false;
} else job_est.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' +
phone.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
<body>
<div class="block">
<div class="done">
<b>Thank you !</b> We have received your message.
</div>
<div class="form">
<form method="post" action="process.php">
<h4><u>Basic Contact Details</u></h4>
<div style="display: inline-block;" class="element">
<label>Name</label><input type="text" name="name"/>
</div>
<div style="display: inline-block;" class="element">
<label>Last Name: </label><input type="text" name="l_name"/>
</div>
<div class="element">
<label>Phone Number</label>
<input type="text" name="phone"/>
</div>
<div class="element">
<label>Email</label>
<input type="text" name="email"/>
</div>
<div style="display: inline-block;" class="element">
<label>Postcode: </label><input type="text" name="postcode" size="10" maxlength="10">
</div>
<div style="display: inline-block;" class="element">
<label>House Number: </label><input type="text" name="house_number" size="3">
</div>
<div style="display: inline-block;" class="element">
<label>Street Name: </label><input type="text" name="street">
</div>
<div style="display: inline-block;" class="element">
<label>County:</label>
<select>
<option name="select">--SELECT--</option>
<option name="bedford">Bedford</option>
<option name="dunstable">Dunstable</option>
<option name="luton">Luton</option>
</select>
</div>
<h4><u>Job Details</u></h4>
<div class="element">
<label>You Would Like To Book A:</label>
<select name="job_est">
<option name="select">--SELECT--</options>
<option name="job">Job</option>
<option name="est">Estimation</option>
</select>
</div>
<br/>
<div class="element">
<label>Service Your Booking:</label>
<select>
<option name="select">--SELECT--</option>
<option name="gardening">Gardening</option>
<option name="landscaping">Landscaping</option>
<option name="painting">Painting & Decorating</option>
<option name="decking">Decking & Fencing</option>
</select>
</div>
<br/>
<div class="element">
<label>Any Additional Information </label>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
</div>
<div class="clear"></div>

You should change selectbox's name attribute with value
<select name="job_est">
<option value="select">--SELECT--</options>
<option value="job">Job</option>
<option value="est">Estimation</option>
</select>
and in your javascript, it should be
if (job_est.val() == 'select') {
job_est.addClass('hightlight');
return false;
}

Related

contact form in html and javascript

I would like to ask you for help.
I created a contact form in HTML and JavaScript, but when I try to send the email, it just doesn't do anything, nothing happens.
See the code below:
/*----------------------------------------------------*/
/* contact form
------------------------------------------------------*/
$('form#contactForm button.submit').click(function() {
$('#image-loader').fadeIn();
var contactName = $('#contactForm #contactName').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- form -->
<form action="mailto:yuridiamond#icloud.com" method="post" enctype="multipart/form-data" id="contactForm" name="contactForm">
<fieldset>
<div>
<label for="contactName">Nome <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactName" name="contactName">
</div>
<div>
<label for="contactEmail">E-mail <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactEmail" name="contactEmail">
</div>
<div>
<label for="contactSubject">Assunto</label>
<input type="text" value="" size="35" id="contactSubject" name="contactSubject">
</div>
<div>
<label for="contactMessage">Mensagem <span class="required">*</span></label>
<textarea cols="50" rows="15" id="contactMessage" name="contactMessage"></textarea>
</div>
<div>
<button class="submit" action="mailto:yuridiamond#icloud.com">Enviar</button>
<span id="image-loader">
<img alt="" src="images/loader.gif">
</span>
</div> -->
</fieldset>
</form>
<!-- Form End -->
I hope you can help me.
Thank you in advance.
I apologize if it's a simple problem, but I'm still new to programming.
$(document).ready(function(){
$('.submit').click(function() {
$('#image-loader').fadeIn();
var contactName = $('#contactForm #contactName').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
});
I found a solution, faster, simpler and very cool.
See the code below:
<form action="https://formspree.io/f/mbjwrqov" method="POST" enctype="multipart/form-data" id="contactForm" name="contactForm">
<fieldset>
<div>
<label for="contactName">Nome <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactName" name="Nome">
</div>
<div>
<label for="contactEmail">E-mail <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactEmail" name="Email">
</div>
<div>
<label for="contactSubject">Assunto</label>
<input type="text" value="" size="35" id="contactSubject" name="Assunto">
</div>
<div>
<label for="contactMessage">Mensagem <span class="required">*</span></label>
<textarea cols="50" rows="15" id="contactMessage" name="Mensagem"></textarea>
</div>
<div>
<button class="submit">Enviar</button>
<span id="image-loader">
<img alt="" src="images/loader.gif">
</span>
</div>
</fieldset>
</form>
<!-- Form End -->
Formspree
http://formspree.io/
The site itself already creates HTML, and I just had to comment on the JavaScript part so as not to give problem or conflict.
Basically, the site already does the intermediary.
A note: The site I created is hosted on GitHub Pages.

JS ajax event to by input change

I would like to have this code so I because if I go into the other input field, the other is updated
Or secound better input change
// on click search results...
$(document).on("touchend", "#ean", function() {
var value = $("#ean").val();
if (value.length != 0) {
//alert(99933);
searchData(value);
} else {
$('#search-result-container').hide();
}
});
// This function helps to send the request to retrieve data from mysql database...
function searchData(val) {
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="app/ajax-artstk/preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
$.post('app/ajax-artstk/controller.php', {
'ean': val
}, function(data) {
if (data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'><div class=\"alert alert-danger\" role=\"alert\">No Result Found...</div></div>");
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
});
}
<form action="#" method="POST" autocomplete="off">
<div class="form-group">
<input type="hidden" name="ausgang">
<div class="row">
<div class="col-md-2">
<label class="control-label"></label>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-2">
<label for="ean" class="control-label">EAN</label>
</div>
<div class="col-md-4">
<input type="text" name="ean" class="form-control" id="ean" value="" maxLength="100" autofocus>
<div id="search-result-container" style="border:solid 0px #BDC7D8;display:none; "></div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<label for="stueck" class="control-label">- Stück</label>
</div>
<div class="col-md-2">
<input type="text" name="stk" class="form-control" id="stk" value="" maxLength="3">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-success">Entnehmen</button>
<button type="reset" class="btn btn-danger">S</button>
<!-- PRINTBUTTON -->
</div>
</div>
</div>
<!-- END form-group -->
</form>
who can help me please who the very nice of you have already tried everything so far
I want to use that via Android and Windows 7 Firefox browser.
I thank you very much for the help that I get I would like to ask to send any links where it is poorly explained
<script>
// on click search results...
$('body').on('change', '#ean', function() {
var value = $("#ean").val();
if (value.length != 0) {
//alert(99933);
searchData(value);
} else {
$('#search-result-container').hide();
}
});
// This function helps to send the request to retrieve data from mysql database...
function searchData(val){
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="app/ajax-artstk/preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
$.post('app/ajax-artstk/controller.php',{'ean': val}, function(data){
if(data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'><div class=\"alert alert-danger\" role=\"alert\">No Result Found...</div></div>");
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
});
}
</script>

Submit form not working when using jQuery

I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>

How to specify minlength in jquery?

If the status value is completed then comment field is required is working good.But the problem is, I want to specify comment field is required for minimum of 50 character.
The Below code: index.php
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Status</label>
<div class="col-md-4">
<select id="status" name="status[]" class="form-control" >
<option value="Pending">Pending</option>
<option value="Work in process">Work in process</option>
<option value="Completed">Completed</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Comment</label>
<div class="col-md-4">
<input id="commentss" name="comment[]" type="text" placeholder="" class="form-control input-md" />
</div>
</div>
<div class="col-md-8 col-sm-12 col-24">
<div class="input_fields" style="color:black">
<button class="add_field btn " onclick="incrementValue()" >Add More</button>
<div>
<input type="text" name="mytextt[]" hidden="" ></div>
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
if ($("#status").val() == "Completed") {
$("#commentss").attr("required", "required");
}
else
$("#commentss").attr("required", false);
});
});
</script>
Use length to find the length of the string
if($('#commentss').val().length < 50){
alert("Please enter 50 characters atleast");
} else {
//submit
}
For this please use below code :
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
var commenttext = document.getElementById('commentss').value;
if (commenttext.length < 50)
{
alert("Please Enter minimum 50 character!")
}
else
{
//Add code
}
});
});
</script>
In Jquery ...
For Dynamic Tracking ...
(You can use blur or keyup even too.)
$(function() {
//disable submit if you want to
$('#commentss').on('input', function(e) {
if(this.value.length >= 50) {
//success
} else {
//fail?
}
});
});
To Validate on Click only ...
Go with the answer of Thamaraiselvam.

Repeating data after form submit

I have 4 links ( view car, hand car, retrieve car and add car). Every link is load by Ajax. The problem is in (add car), the first time I click submit the data gets recorded in the database once ... when I click (view car) and go back to (add car) and submit the form again it adds the data to the database 3 times. Also when I press (view car) and back to add car and submit the from again it records the data 6 times.
ajax.js
$(document).ready(function(){
$('#viewCar').click(function(){
$("#show").load('view');
});});//end click
$(document).ready(function(){
$('#handCar').click(function(){
$("#show").load('handcar');
});//end load
});//end click
$(document).ready(function(){
$('#retrieveCar').click(function(){
$("#show").load('retrieve');
});//end load
});//end click
$(document).ready(function(){
$('#addCar').click(function(){
enter code here $("#show").load('add');
});//end load
});//end click
$(document).ready(function(){
$("#submit").click(function(e)
{
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '')
{
console.log('error some form is empty !!');
}
else
{
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function()
{
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
}); //end click
}); //end of ready
car_links.html
<div class="container">
<ul class="ul">
<li class="li"><a id="viewCar" href="#" >view cars</a></li>
<li class="li"><a id="handCar" href="#">hand car</a></li>
<li class="li"><a id="retrieveCar" href="#">retrieve car</a></li>
<li class="li"><a id="addCar" href="#">add a car</a></li>
</ul>
car_add.html
<div class="col-md-4 col-md-offset-4">
<form id="cForm" class="form-horizontal" >
<?php echo validation_errors(); ?>
<legend>add a new car</legend>
<div class="form-group">
<label class="col-sm-5 control-label" for="LN">License #:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LN" name="LN" value="" /></li>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="LT">License Ltr:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LT" name="LT" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Model">Model:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Model">
<option value="Toyota"> Toyota</option>
<option value="Audi"> Audi</option>
<option value="Hundai"> Hundai</option>
<option value="BMW"> BMW</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Year"> Year:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Year">
<option value="2010"> 2010</option>
<option value="2014"> 2014</option>
</select>
</div>
</div>
<div class="form-actions btn-action">
<button class="btn btn-success" id="submit" value="save" type="button" name="submit">save</button></li>
<button class="btn btn-danger" type="reset" name="reset"> Reset </button></li>
</div>
</form>
</div>
For starters you have each click function in its own .ready function. The .ready function is initiated when the page is loaded. If you want the function to load only on a click then you need to place the click function into a function like this.
$(function() {
$('#viewCar').click(function() {
$("#show").load('view');
});
$('#handCar').click(function() {
$("#show").load('handcar');
});
$('#retrieveCar').click(function() {
$("#show").load('retrieve');
});
$('#addCar').click(function() {
$("#show").load('add');
});
$("#submit").click(function(e) {
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '') {
console.log('error some form is empty !!');
} else {
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function() {
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
});
}
If that doesn't work or is not what you wanted please leave me a comment.

Categories

Resources