Need to show the thankyou message instead of ajax response - javascript

I was trying to do the form submit response, like on submit the form fields should be hidden and to show the thank you message without refreshing the page, but when i click submit the page is getting refreshed and showing the ajax response {"result":"success","data":"{\"message\":[\"sample message\"]}"
tried using Send Email from a Static HTML Form using Google Apps Mail!
(function() {
'use strict';
function getFormData(form) {
var elements = form.elements;
var fields = Object.keys(elements).filter().map(function(k) {
if (elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
} else if (elements[k].length > 0) {
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name) {
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
//formData.formGoogleSend = form.dataset.email || ""; // no email by default
formData.formPage = form.dataset.page || "";
}
function handleFormSubmit(event) {
if (this.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
this.classList.add('was-validated');
} else if (this.checkValidity() === true) {
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
return;
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
}
function loaded() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener("submit", handleFormSubmit, false);
});
}
document.addEventListener("DOMContentLoaded", loaded, false);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>
I expect to show the thankyou message without refreshing the page but the actual result is the page getting refreshed and showing the Ajax response

move event.preventDefault(); out of the if statement so the default submit action of the form is never triggered. You don't want to do an submit when you do an ajax request since the submit action will navigate to the form action url.
$('.needs-validation').on('submit', handleFormSubmit);
function handleFormSubmit(event) {
event.preventDefault();
if (this.checkValidity() === true) {
//Do this in the ajax succes event handler
$('.thankyou_message').show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="gform needs-validation" method="POST" data-page="form validation test" action="https://script.google.com/macros/s/AKfycbxXw4fshxotq4vkQ3LUjvBaHhjS2RjFvDvKs5FW4w/exec" novalidate>
<div class="form-elements col-md-6 m-5">
<div class="form-row">
<div class="col-md-12 mb-3">
<textarea id="visitorMessage" class="form-control" name="message" placeholder="Message" required></textarea>
<div class="invalid-tooltip"> Please enter the message </div>
</div>
</div>
<button class="btn btn-primary btn-sm mx-0" type="submit">Submit</button>
</div>
<div class="thankyou_message" style="display: none;">
<h2>Thanks for contacting us! We will get back to you soon!</h2>
</div>
</form>

Related

ValidateForm How to validate and show text when submit button was clicked in JavaScript

I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>

Buttons do not work and page keeps loading after POST method

I have page for changing password and after sending POST request to backend. I add additional element Login so that user could go back to login page and login. However neither this, nor Cancel button doesn't do anything. After I click on it the page starts loading but stays always the same - doesn't redirect to the login page. If I copy that link and open in new page and click Cancel then, it works fine. Here's my code:
document.getElementById("btn_cancel").onclick = function () {
window.location.replace("/login");
};
var token = window.location.href.substring(window.location.href.lastIndexOf("/") + 1);
function validate() {
var responseText = document.getElementById('error_id');
var password = document.forms["reset-pasword"]["new_password"].value;
var confirmPassword = document.forms["reset-pasword"]["repeat_password"].value;
if (password !== confirmPassword) {
error = "Passwords do not match";
responseText.innerHTML = error;
responseText.className = "error_text";
return false;
}
return true;
}
document.getElementById("btn_change").onclick = function (event) {
var responseText = document.getElementById('error_id');
if (validate() != true)
return;
var password = document.getElementById("new_password").value;
var request = {
token: token,
password: password
};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/v1/Auth/UpdatePassword', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = (res) => {
response = res['target']['response'];
if (response) {
response = JSON.parse(response);
responseText.innerHTML = response.message;
responseText.className = "error_text";
} else {
responseText.innerHTML = "Password changed succesfully. Login";
responseText.className = "success_text";
}
};
xhr.send(JSON.stringify(request));
event.preventDefault();
};
<div id="change_password_panel">
<form name="reset-pasword" id="reset-pasword">
<label for="password">New password</label>
<input type="password" placeholder="New Password" id="new_password" name="new_password" required />
<label for="password">Repeat new password</label>
<input type="password" placeholder="Repeat Password" id="repeat_password" name="repeat_password" required />
<div style="width: 100%; display: inline-block;margin-top: 10px;">
<div style="float: left;"><button id="btn_change" class="button" type="button">Change
password</button></div>
<div style="float: right;"><button id="btn_cancel" type="button" class="button">Cancel</button></div>
</div>
<p id="error_id"></p>
</form>
</div>
what could be wrong here?
Both cancel and Change password buttons seem same to me but I can click Change password multiple times and when I click cancel page just keeps loading.
I've also tried:
document.getElementById("btn_cancel").onclick = function (event) {
event.preventDefault();
window.location = "http://localhost:4200/";
};
nothing works...
Clicking on the cancel button works correctly.
As for the Change password button, check the xhr.onload function. On success, you need to render "Password changed succesfully. Login" inside in an html element; something like document.getElementById("resultDiv").innerHTML="Password changed succesfully. Login", at the moment you're just updating the value of responseText.innerHTML but responseText is not defined anywhere.
responseText is not defined. You are trying to change the text of same button so for that you need to have a reference of it.
<script type="text/javascript">
document.getElementById("btn_cancel").onclick = function () {
window.location.replace("/login");
};
var token = window.location.href.substring(window.location.href.lastIndexOf("/") + 1);
var button = document.getElementById("btn_change");
button.onclick = function () {
var password = document.getElementById("new_password").value;
var request = {
token: token,
password: password
};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/changePassword', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = (res) => {
response = res['target']['response'];
if (response) {
response = JSON.parse(response);
button.innerHTML = response.message;
button.className = "error_text";
} else {
button.innerHTML = "Password changed succesfully. Login"
button.className = "success_text"
}
};
xhr.send(JSON.stringify(request));
};
<div id="change_password_panel">
<form name="reset-pasword" id="reset-pasword">
<label for="password">New password</label>
<input type="password" placeholder="New Password" id="new_password" name="new_password" required />
<label for="password">Repeat new password</label>
<input type="password" placeholder="Repeat Password" id="repeat_password" name="repeat_password" required />
<div style="width: 100%; display: inline-block;margin-top: 10px;">
<div style="float: left;"><button id="btn_change" class="button" type="button">Change
password</button></div>
<div style="float: right;"><button id="btn_cancel" type="button" class="button">Cancel</button></div>
</div>
<p id="error_id"></p>
</form>
</div>
What do you want to do in onload callback? if you want to redirect to login page, you should use window.location.href
document.getElementById("btn_cancel").onclick = function (event) {
event.preventDefault();
window.location = "http://localhost:4200/";
};
You forgot href, window.location.href is right

Display textbox multiple times

The HTML part contains a textarea with a label.The user has to enter text and the form should be submitted and refreshed for the user to enter text again for say 5 more times. How can I do this using Javascript?
This is the html code:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</form>
<button type="button" class="btn" id="sub" onclick="func()">Next</button>
The javascript code:
var x=1;
document.getElementById("p1").innerHTML="Question"+x;
function func()
{
var frm = document.getElementsByName('myform')[0];
frm.submit();
frm.reset();
return false;
}
Here are two methods you can use. Both of these require you to add a submit button to your form, like this:
<form name="myform" method="post">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
<!-- add this button -->
<input type="submit" value="Submit" class="btn">
</form>
<!-- no need for a <button> out here! -->
Method 1: sessionStorage
sessionStorage allows you to store data that is persistent across page reloads.
For me info, see the MDN docs on sessionStorage. This method requires no external libraries.
Note that in this method, your page is reloaded on submit.
window.onload = function() {
var myForm = document.forms.myform;
myForm.onsubmit = function(e) {
// get the submit count from sessionStorage OR default to 0
var submitCount = sessionStorage.getItem('count') || 0;
if (submitCount == 5) {
// reset count to 0 for future submissions
} else {
// increment the count
sessionStorage.setItem('count', submitCount + 1);
}
return true; // let the submission continue as normal
}
// this code runs each time the pages loads
var submitCount = sessionStorage.getItem('count') || 0;
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
};
Method 2: AJAX with jQuery
If you don't mind using jQuery, you can easily make AJAX calls to submit your form multiple times without reloading.
Note that in this example your page is not reloaded after submit.
window.onload = function() {
var myForm = document.forms.myform;
var submitCount = 0;
myForm.onsubmit = function(e) {
$.post('/some/url', $(myForm).serialize()).done(function(data) {
submitCount++;
});
console.log('You have submited the form ' + submitCount + ' times');
if (submitCount == 4) {
console.log("This will be the final submit! This is the part where you change the submit button text to say \"Done\", etc.");
}
e.preventDefault();
return false;
};
};
Hope this helps!
You shuld create an array and push the value of the textbox to the array in func().
We can create a template using a <script type="text/template>, then append it to the form each time the button is clicked.
const btn = document.getElementById('sub');
const appendNewTextArea = function() {
const formEl = document.getElementById('form');
const textareaTemplate = document.getElementById('textarea-template').innerHTML;
const wrapper = document.createElement('div');
wrapper.innerHTML = textareaTemplate;
formEl.appendChild(wrapper);
}
// Call the function to create the first textarea
appendNewTextArea();
btn.addEventListener('click', appendNewTextArea);
<form name="myform" method="post" id="form">
</form>
<button type="button" class="btn" id="sub">Next</button>
<script id="textarea-template" type="text/template">
<div class="form-group col-sm-5">
<label for="ques"><p id="p1">Question:</p></label>
<textarea class="form-control" rows="5" id="ques"></textarea>
</div>
</script>

JS wont recognize a variable within angular controller object

Im trying to create a simple login verification, however the validation function seizes to function when the validation comparison begins, and the console sais that the variable "userName is not defined" although it clearly is.
Can enyone tell me what am i defining wrong?
the angular controller code:
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
this.userName = "";
this.password = "";
this.userNameValid = true;
this.passwordValid = true;
/*submit the form*/
this.submit = function () {
alert("submit");
this.validate();
};
/* make sure user name and password has been inserted*/
this.validate = function () {
alert("validate");
var result = true;
this.userNameValid = true;
this.passwordValid = true;
if (this.userName == "") {
alert("username="+userName);
this.userNameValid = false;
result = false;
}
if (this.password == "") {
this.passwordValid = false;
result = false;
}
alert("validuserNameValid==" + userNameValid + " passwordValid==" + passwordValid);
return result;
};
});
the HTML form:
<body ng-app="LoginApp" ng-controller="LoginController as LoginController">
<form role="form" novalidate name="loginForm" ng-submit="LoginController.submit()">
<div id="loginDetails">
<div class="form-group">
<label for="user"> User Name:</label>
<input type="text" id="user" class="form-control" ng-model="LoginController.userName" required />
<span ng-show="LoginController.userNameValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" id="password" class="form-control" ng-model="LoginController.password" required />
<span ng-show="LoginController.passwordValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
{{"entered information:" +"\n"+LoginController.userName+" "+ LoginController.password}}
</div>
</div>
</form>
</body>
the log:
Error: userName is not defined
this.validate#http://localhost:39191/login.js:23:13
this.submit#http://localhost:39191/login.js:11:9
anonymous/fn#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js line 231 > Function:2:292
b#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:126:19
Kc[b]</<.compile/</</e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:195
uf/this.$get</m.prototype.$eval#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:103
uf/this.$get</m.prototype.$apply#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:335
Kc[b]</<.compile/</<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:245
Rf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:37:31
Qf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:36:486
Always use this judiciously. I would recommend you to store the reference of this in variable then use it wherever required.
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
//Store the reference of this in a variable
var lc = this;
//Use the stored refrence
lc.userName = "";
/* make sure user name and password has been inserted*/
lc.validate = function () {
if (lc.userName == "") {
alert("username="+userName);
lc.userNameValid = false;
result = false;
}
};
});
inside your alert boxes you have not mentioned this.userName try removing the alert boxes or change them.

Validation in Jquery ajax form submission

I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>
The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});
In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.

Categories