How to make input.error work on all fields? - javascript

http://jsfiddle.net/Nvt2h/
I am using this script which sends details from input fields to my email. As you can see, there is input.error which highlights the field in red if there is an incorrect entry. However, this currently works only for Field 1 and Field 4.
How can I make this work on field 2 and 3 as well ?
<form id="contact" name="contact" action="#" method="post">
<div class="form-group">
<label for="msg">Field1:
</label>
<input name="msg" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="id">Field2:</label>
<input name="id" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="pb">Field3:
</label>
<input name="pb" type="msg" class="form-control" id="pb">
</div>
<div class="form-group">
<label for="email">Field4:</label>
<input name="email" type="email" class="form-control" id="email">
</div>
<button id="send">Submit</button>

Add a minlength attribute to those input fields
<input name="msg" type="msg" class="form-control msg" id="msg" minlength="2">
then
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\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,}))$/;
return reg.test(email);
}
$(document).ready(function () {
//$(".modalbox").fancybox();
$("#contact").submit(function () {
return false;
});
$("#send").on("click", function () {
$('#contact input.error').removeClass('error');
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#email").addClass("error");
}
var minlen = $('#contact input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
type: 'POST',
url: 'send.php',
data: $("#contact").serialize(),
dataType: 'jsonp',
success: function (data) {
if (data.result == true) {
$("#contact").fadeOut("fast", function () {
$(this).before("<p class='success'><strong>Thank you, your message has been sent. We will be in touch shortly.</strong></p>");
});
} else { /* if you want to handle mail send failed, put it here */
}
},
error: function (jqXHR, textStatus, errorThrown) {
// this is triggered if there's a problem getting the jsonp back from the server
}
});
}
});
});
Demo: Fiddle

Related

how to change button text with 'Loading' after submit form and reset form after submit in angular

var app = angular.module('snc', []);
app.controller('contactForm', function($scope, $http) {
$scope.user = {};
$scope.submitForm = function() {
$http({
method: 'POST',
url: 'php-form/form.php',
data: $scope.user,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
if (!data.success) {
if ($scope.errorName = data.errors.name) {
$(".alert-set").removeClass('alert-danger');
$(".alert-set").removeClass('alert-success');
$(".alert-set").fadeIn(1000);
$(".alert-set").removeClass("hide");
$(".alert-set").fadeOut(5000);
$(".alert-set").addClass('alert-warning');
$(".Message-txt").text(data.errors.name);
} else if ($scope.errorMobile = data.errors.mobile) {
$(".alert-set").removeClass('alert-danger');
$(".alert-set").removeClass('alert-success');
$(".alert-set").fadeIn(1000);
$(".alert-set").removeClass("hide");
$(".alert-set").fadeOut(5000);
$(".alert-set").addClass('alert-warning');
$(".Message-txt").text(data.errors.mobile);
} else if (data.errors.email == 'fail') {
$(".alert-set").removeClass('alert-danger');
$(".alert-set").removeClass('alert-success');
$(".alert-set").fadeIn(1000);
$(".alert-set").removeClass("hide");
$(".alert-set").fadeOut(5000);
$(".alert-set").addClass('alert-warning');
$(".Message-txt").text('Sorry, Failed to send E-mail.');
} else {
$(".alert-set").removeClass('alert-warning');
$(".alert-set").removeClass('alert-success');
$(".alert-set").fadeIn(1000);
$(".alert-set").removeClass("hide");
$(".alert-set").fadeOut(5000);
$(".alert-set").addClass('alert-dnager');
$(".Message-txt").text('somthing went wrong please try again.');
}
} else {
$(".alert-set").removeClass('alert-danger');
$(".alert-set").removeClass('alert-warning');
$(".alert-set").fadeIn(1000);
$(".alert-set").removeClass("hide");
$(".alert-set").fadeOut(5000);
$(".alert-set").addClass('alert-success');
$(".Message-txt").text(data.message);
this.submitForm = {};
}
});
};
});
<form name="queryForm" ng-submit="submitForm()" novalidate>
<div class="form-group">
<label for="Name">Name:<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="user.name" id="name" placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="Mobile">Mobile:<span class="text-danger">*</span></label>
<input type="number" class="form-control" ng-model="user.mobile" id="mobile" placeholder="Enter Your Mobile Number">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" ng-model="user.email" id="email" placeholder="Enter Your Email">
</div>
<div class="form-group">
<label for="Message">Message:</label>
<textarea type="text" class="form-control" ng-model="user.message" id="name" placeholder="Enter Your Message" rows="4"></textarea>
</div>
<button type="submit" class="btn btn-snc">Submit</button>
<div class="alert alert-dismissible alert-set">
<strong class='Message-txt'></strong>
</div>
</form>
I have a simple contact form it has to send query data to php page and I want to disable button and change button text after submitting form and also full form reset after submit. I tried but I always get some type of angular error. Can you help me to solve it and if you are a Angular Developer then can you please check this form and let me know if I need to change something.
To reset the form, you could use something like:
(Mind: you've got two name ID. An ID should be UNIQ on your page).
function onSubmit()
{
$('#submit_button').text('Loading…');
resetForm();
}
function resetForm()
{
for(let id of ['name','mobile','email', 'message'])
{
$("#"+id).val('');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="queryForm" ng-submit="submitForm()" novalidate>
<div class="form-group">
<label for="Name">Name:<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="user.name" id="name" placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="Mobile">Mobile:<span class="text-danger">*</span></label>
<input type="number" class="form-control" ng-model="user.mobile" id="mobile" placeholder="Enter Your Mobile Number">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" ng-model="user.email" id="email" placeholder="Enter Your Email" value="some text">
</div>
<div class="form-group">
<label for="Message">Message:</label>
<textarea type="text" class="form-control" ng-model="user.message" id="message" placeholder="Enter Your Message" rows="4">Some text</textarea>
</div>
<button id="submit_button" type="button" class="btn btn-snc" onclick="onSubmit()">RESET FORM</button>
<div class="alert alert-dismissible alert-set">
<strong class='Message-txt'></strong>
</div>
</form>
An assignation is not a comparison:
$scope.errorName = data.errors.name ;
… is an assignation which means: put the data.errors.name into the $scope.errorName variable.
$scope.errorName == data.errors.name
… is a comparison which means: data.errors.name is equal to $scope.errorName.
If you use an assignation instead of a comparison, the result will always be true as long as the value is true-like.
So:
if ( a = 1 ) { /* always true */ }
if ( a == 1 ) { /* true only if `a` is equal to 1 */
if ( a === 1 ) { /* true only if `a` is strictly equal to 1 */
if ( a = "false" ) { /* always true (a string not empty is true) */ }
if ( a == "false" ) { /* true only if `a` is equal to "false" */
if ( a === "false" ) { /* true only if `a` is strictly equal to "false" */
The strictly above means of the same type. For instance:
1 == "1" // => true
1 === "1" // => not true. The Former is a Number, the latter is
// a String.
You should avoid the typo like:
$(".alert-set").addClass('alert-dnager');
To avoid it, try to keep your code as clean as possible. You'll be able to avoid a lot of errors, you'll have a better understanding of your code, and other people can help you more efficiency.
Your if error statement could become:
.success(function(data) {
console.log(data);
if ( false === data.success) {
// Typo error avoiding: NOT plain-text USE variables
let alertClass = '.alert-set';
let errMessage = '' ;
// Reduce the amount of code
$(alertClass)
.addClass('alert-warning')
.removeClass('alert-success')
.fadeIn(1000)
.removeClass("hide")
.fadeOut(5000)
.removeClass('alert-danger') ;
// Treat only what you have to treat
// You could use a lambda function, too:
// let errMessage = function(val){ return ... }(actual value);
if ( $scope.errorName == data.errors.name )
{
errMessage = data.errors.name ;
}
else if ( $scope.errorMobile == data.errors.mobile )
{
errMessage = data.errors.mobile ;
}
else if (data.errors.email == 'fail')
{
errMessage = 'Sorry, Failed to send E-mail.';
}
else {
errMessage = 'somthing went wrong please try again.' ;
}
// Only one action
$(".Message-txt").text(errMessage) ;
Now we can work ;-).
Keep in mind that we don't want to help you if your code is not clean and if we can't understand at a first glance what's going on.

JQuery regex email validation preventing form from submitting

I have a 'contact us' form on our website, people fill out name, email, and message and hit send. Currently the form won't submit if I have the email validation in my code.
Here is HTML form code:
<form role="form" id="feedbackForm">
<div class="form-group">
<label class="control-label" for="name">Full Name *</label>
<div class="input-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter your name.</span>
</div>
<div class="form-group">
<label class="control-label" for="email">Email Address *</label>
<div class="input-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="reason">Contact Reason *</label>
<select name="reason" class="form-control" required>
<option value="General Inquiry">General Inquiry</option>
<option value="Schedule Appointment">Schedule Appointment</option>
<option value="Report Issue">Report Issue</option>
<option value="Provide Feedback">Provide Feedback</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="message">Message *</label>
<div class="input-group">
<textarea rows="5" class="form-control" id="message" name="message" placeholder="Enter Your Message" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="mykey"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback
</button>
</div>
</form>
and here's the jquery code:
(function () {
//using regular expressions, validate email
var contactFormUtils = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
//if no form errors, remove or hide error messages
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
//upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
clearForm: function () {
$('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
$('#feedbackForm input,textarea').val("");
grecaptcha.reset();
},
//when error, show error messages and track that error exists
addError: function ($input) {
var parentFormGroup = $input.parents('.form-group');
parentFormGroup.children('.help-block').show();
parentFormGroup.addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$(document).ready(function() {
$("#feedbackSubmit").click(function() {
var $btn = $(this);
$btn.button('loading');
contactFormUtils.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
//use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
var $form = $("#feedbackForm"),
hasErrors = false;
if ($form.validator) {
hasErrors = $form.validator('validate').hasErrors;
} else {
$('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
hasErrors = true;
contactFormUtils.addError($(this));
}
});
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
}
//if there are any errors return without sending e-mail
if (hasErrors) {
$btn.button('reset');
return false;
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "php/sendmail.php",
data: $form.serialize(),
success: function(data) {
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
},
complete: function() {
$btn.button('reset');
}
});
return false;
});
$('#feedbackForm input, #feedbackForm textarea').change(function () {
var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
if ($(this).val()) {
checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
} else {
checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
}
});
});
})();
When I remove this bit of code that validates if the email is in correct format then the form sends to my email right away.
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
Which in turn leads to this bit, I believe :
if (hasErrors) {
$btn.button('reset');
return false;
}
if I comment out 'return false;' then it sends the form
I can't find what part of the email validation prevents the form from submitting?
Maybe you have another element with id="email" somewhere.
Maybe try:
$('#feedbackForm input[type=email]').each(function() {
if (!contactFormUtils.isValidEmail(this.val())) {
hasErrors = true;
contactFormUtils.addError(this);
console.log("ERROR: Invalid email: "+this.val()+" in input "+this.attr("name"));
}
})

Submitting two forms separately in one page with separate thankyou message

I've a page which have two different forms:
Form 1:
<form id="info-form" method="POST" action="">
<label for="name">What is your Name? </label>
<input required type="text" name="name" placeholder="Enter your full name here." />
<label for="email">What is your email ID? </label>
<input required type="email" name="email" placeholder="your.name#email.com" />
<label for="mobile-number">What is your 10-Digit Mobile Number? </label>
<input required type="text" name="mobile-number" maxlength="10" placeholder="Enter num." />
<label for="posting-place">What is your current place of residence? </label>
<input type="text" name="place" placeholder="Enter your current residing place here." />
<button type="submit" class="btn btn-lg btn-success">
  Submit
</button>
<button type="reset" class="btn btn-lg btn-warning">
Reset
</button>
</form>
Form 2:
<form id="contact-form" method="POST" action="">
<label for="name">What is your Name? </label>
<input type="text" name="name" placeholder="Enter your full name here." />
<label for="email">What is your email ID? </label>
<input type="email" name="email" placeholder="your email" />
<label for="message"> Your Message: </label>
<textarea id="message" name="message" rows="5" placeholder="Type in your message here"></textarea>
<button id="submit_button" type="submit" class="btn btn-lg btn-success">
Send
</button>
<button id="reset_button" type="reset" class="btn btn-lg btn-warning">
Reset
</button>
</form>
I then have these below thank you messages after the closing form tag of both the above two forms
Thank you message after submitting Form 1:
<div style="display:none;" id="thankyou_form">
<p><em>Thank You</em> for submitting!</p>
</div>
Thank you message after submitting Form 2:
<div style="display:none;" id="thankyou_contact">
<p><em>Thank You</em> for contacting! We will get back to you soon!</p>
</div>
I then have two script for displaying the thank you message on the same page after the form is submitted.
<script type="text/javascript">
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_contact").style.display = "inline";
}
else
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_contact").style.display = "none";
}
}
});
});
});
</script>
But when I submit the second form the thankyou message is also displayed is the first form. Also, the form is submitted twice.
Can you please inform me how to identify both the javascript separately? Or, Can I combine both the script into one but both submit buttons working independently of each other?
It would be very much helpful and also enlightening for me if you can point out my mistake.
P.S. I'm a beginner.
Edit1: The javascript code was modified (but currently non-working) as per suggestion from David. The new code is:
<script type="text/javascript">
$(function ()
{
$('form').submit(function (e)
{
if(e.target === 'form#info-form')
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
document.getElementById("thankyou_info").style.display = "inline";
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
}
}
});
}
if(e.target === 'form#contact-form')
{
e.preventDefault();
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (response)
{
console.log(response);
if(response.result == 'success')
{
document.getElementById("thankyou_contact").style.display = "inline";
}
else
{
document.getElementById("thankyou_contact").style.display = "none";
document.getElementById("sorry_contact").style.display = "inline";
}
}
});
}
});
});
</script>
Use event.target to determine which form is getting submitted, You need to refine your code as,
if(response.result == 'success')
{
// Determine if the submission came from "Info Form" or "Contact Form"
if(e.target === 'form#info-form')
{
document.getElementById("thankyou_form").style.display = "inline";
}
else
{
document.getElementById("thankyou_contact").style.display = "inline";
}
}
else
{
// this is for the second form. For the 1st form ID is changed to thankyou_form
document.getElementById("thankyou_form").style.display = "none";
document.getElementById("thankyou_contact").style.display = "none";
}

Show javascript variable in html div

Once a form is submitted my javascript hides one div and shows another:
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
The bottom line is where I'm trying to add some text to the div that is dynamically displayed. However, nothing is displayed in the div. I'd also like to show the variable from another function in the same file.
it's the var e = $("#username").val(); from the code below which I would like to add to the div eventually.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin() {
var e = $("#username").val();
var p = $("#password").val();
if(e != "" && p != "") {
$.ajax({
type: 'POST',
url: 'http://localhost/php/log.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
if (response.success) {
$.mobile.changePage("#loginTest");
}
else {
alert("Your login failed");
}
},
error: function(error){
alert('Could not connect to the database' + error);
}
});
}
else {
alert("You must enter username and password");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
HTML Code:
<body>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="button" value="Login" id="submitButton" onclick="handleLogin()">
<div data-role="footer">
</div>
</div>
<div id="loginTest" data-role="page">
<div id="name">
</div>
</div>
</body>
try this on element id loginTest (#loginTest)
document.getElementById('loginTest').innerHTML= your variable here; //or any string
if you are using jquery
$( '#loginTest' ).text( your variable ); //or any string
Wouldn't you be better to restrict the post back:
<input type="button" value="Login" id="submitButton" onClientClick="handleLogin()">
and then return false from the function.

jQuery .submit() .ajax() have to click send button two times to get the correct response

I have a form with 5 fields that i am sending with AJAX to a PHP Script that does some simple validation and returns a string.
I have made a little jQuery script for the actual submission, and when i try to send the form i have to click the send button two times.
Update: Url to live site: http://www.dan-levi.no/new/#!/Kontakt
Here are some code:
HTML
<form id="contact_form" class="form-horizontal" action"includes/contact.php" method"post">
<div class="control-group">
<label class="control-label" for="contact_name">Ditt navn og evt. bedrift</label>
<div class="controls">
<input type="text" class="input-large" id="contact_name" name="contact_name" placeholder="Ditt navn og evt. bedrift" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_email">E-post</label>
<div class="controls">
<input type="email" class="input-large" id="contact_email" name="contact_email" placeholder="E-post" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_tel">Telefon</label>
<div class="controls">
<input type="tel" class="input-large" id="tel" name="contact_tel" placeholder="Telefon" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_subject">Emne</label>
<div class="controls">
<input type="text" class="input-large" id="subject" name="contact_subject" placeholder="Emne for melding" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_desc">Din beskjed</label>
<div class="controls">
<textarea rows="10" class="input-large" id="contact_desc" name="contact_desc" placeholder="Din beskjed"></textarea>
</div>
</div>
<div class="text-error pull-right" id="error_message"></div><br>
<input class="btn btn-large pull-right" type="submit" name="" value="Send" /><br>
</form>
javaScript
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
})
.done(function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
})
e.preventDefault();
});
});
PHP
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_tel = $_POST['contact_tel'];
$contact_subject = $_POST['contact_subject'];
$contact_desc = $_POST['contact_desc'];
if ($contact_name == '' || $contact_email == '' || $contact_tel == '' || $contact_subject == '' || $contact_desc == '') {
echo "empty";
die();
}
echo $contact_name.'<br><br>';
echo $contact_email.'<br><br>';
echo $contact_tel.'<br><br>';
echo $contact_subject.'<br><br>';
echo $contact_desc.'<br><br>';
I cant find out why i have to click the button two times, i have tried some trial and error, read the forum for answers. I tried to serialize the form outsite the submit function, i just cant get this to behave the way i want. All help is greatly appreciated.
Oh, worth to mention. The actual response is that the fields are empty (php validation) the first time i click, but the second time it works as it should.
Make the ajax call using a regular input button instead of a submit button.
$("#button").click(function () { ... ajax ... }
I'm not sure if it makes a difference but have you tried putting what you want to happen afterwards in a success callback?
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
e.preventDefault();
});
});
I'm guessing it's because the default action (submit the form) is processing before your $.ajax request. Try making e.preventDefault() first in your submit callback.
$(document).ready(function() {
$('#contact_form').submit(function(e) {
e.preventDefault();
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
});
});

Categories

Resources