Unable to prevent form when a condition is met - javascript

I am working on a form I wish to validate via jQuery $.ajax. The form should only be submitted if a certain condition, data == 1
var preventSubmit = function() {
return false;
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
return true;
}
}
});
};
$("#comment_form").on('submit', preventSubmit);
The submit happens regardless if the condition is met or not.
Where is my mistake?
If I use e.preventDefault();, how can I "undo" it in case if data is equal to 1?

You won't be able to allow the submission of the form with a return value of true because the ajax is happening asynchronously (by the time it completes the function has already finished executing). What you can do is always prevent the form from submitting in the preventSubmit function, then submit it programmatically.
var preventSubmit = function() {
var form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// if data is equal to 1,
// submit form
if (data == 1) {
form.off();//remove bound events (this function)
form.submit();//manually submit the form
}
}
});
return false;//the return needs to be at the end of the function and will always prevent submission
};
$("#comment_form").on('submit', preventSubmit);

Anything after the return false; will never be executed.
Also, you should be doing form validation on the front-end rather than the back-end. With that being said, you should not remove the validation from the back-end.
One more thing, try doing HTML5 form validation first as that's your first line of defence.
You're looking at something on the lines of:
var validateForm = function(e) {
// prevent the default form action to allow this code to run
e.preventDefault();
var isValid = false,
form = $(this),
name = form.find('#name').val(),
email = form.find('#email').val(),
comment = form.find('#comment').val();
// Validation goes here
// ...
// isValid = true;
if (isValid) {
$.ajax({
type: "POST",
url: absolute_store_link + '/ajax/comments-filter',
data: {
name: name,
email: email,
comment: comment
},
success: function(data) {
// do something with the response. Maybe show a message?
form.submit();
}
});
}
};

Related

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

onSubmit form - Ajax request to validate the form

I have this scenario where when submiting html form we call javascript method to validate the form. Problem is that validation is done through Ajax request calling php function which returns json array which is empty or contains array with errors.
I am using Ajax request as this newValidation function will be used on all forms on my application so all field ids names and stuff is dynamic same as validation messages.
Console log results are:
Undifiend
It should be True or False.
So it looks like .done run after console.log.
I thought .done is waiting until ajax is finished and only then proceed?
Reason why I am asking I need this .done to run first so it can assing answer variable and only then return boolean to the form. Does this even possible?
UPDATED:
Html form:
<form id="systemManagementSettings" action="#" method="POST" onsubmit="return newValidation('systemManagementSettings')">
JavaScript
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
answer = true;
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
answer = false;
}
});
console.log(answer);
return answer;
}
How do you prevent the form from actually being submitted?
Use event.preventDefault().
UPDATE
Submit the form in the done function.
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
$.ajax({
url: $('#'+formId).attr('action'),
type: "POST",
data: {form: $('#'+formId).serializeArray()},
});
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
}
});
return false; //all the time
}

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources