Javascript validation works...and fails - javascript

I have the following Javascript code in my web page that SHOULD ensure data validation and then (if the form is valid) submit the data to an AJAX call:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
}
});
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
The problem is, the validation works, but it doesn't. When the form fields are not valid, it hits this block:
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
and the alert is displayed. The very next line should force the function to exit, stopping execution of any remaining code, but for some reason it doesn't. Instead, the remainder of the code executes as if the form is valid, and the alert for the AJAX failure pops up.
Why does the 'return false' not actually force the function to exit, and what am I missing here?

return false is a statement of the anonymous function function (form) {... which is called for each form element. The anonymous function function (event) {... doesn't have a return statement. The filter function in Array.prototype.filter.call(forms, has to return either true or false for each element to work as expected, not false or undefined. You could use e.g. Array.prototype.every and/or Array.prototype.map instead of Array.prototype.filter:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.map.call(forms, function (form) {
if (!form.checkValidity()) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
return true;
}
});
if (!validation.every(el => el)) return false;
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>

Related

Ajax call is not returning to success from controller

In the code below, I am doing an ajax call and calling a controller '/feedback', and from controller, I am returning a String value as "Y". But everytime, it's redirecting me to error Jsp.
Any help would be appreciated.
Ajax call:
document.getElementById("modal_feedback").addEventListener("submit", function(e) {
var form = this;
var name = form.name.value;
var rating = form.overall.value;
var msg = form.message.value;
if(name == "") {
alert("Please enter your Name");
form.name.focus();
e.preventDefault();
} else if(rating == "") {
alert("Please select a rating");
form.overall[0].focus();
e.preventDefault();
} else if(msg == "") {
alert("Please enter your comment in the Message box");
form.message.focus();
e.preventDefault();
}
$.ajax({
type: "POST",
url: "feedbackData.htm?ratingId="+rating+"&msg="+msg,
success: function(response) {
console.debug(response);
if(response == 'Y'){
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/icon_pdf.png' />");
});
}
}
});
return false;
}, false);
Controller code:
#RequestMapping(value = "/feedbackData")
public #ResponseBody String getFeedbackData(String ratingId, String msg) throws UnsupportedEncodingException{
System.out.println("Inside FeedbackController..");
try{
feedbackService.updateFeedback(ratingId,msg);
return "Y";
}catch(Exception e)
{
logger.error("Exception in Login :" + e);
return "N";
}
}
}
I have tried the datatype:"html" which start returning the response and not taking to the error.jsp. Updated JS code as below
document.getElementById("modal_feedback").addEventListener("submit", function(e) {
e.preventDefault();
var form = this;
var name = form.name.value;
var rating = form.overall.value;
var msg = form.message.value;
if(name == "") {
alert("Please enter your Name");
form.name.focus();
e.preventDefault();
} else if(rating == "") {
alert("Please select a rating");
form.overall[0].focus();
e.preventDefault();
} else if(msg == "") {
alert("Please enter your comment in the Message box");
form.message.focus();
e.preventDefault();
}
$.ajax({
type: "POST",
url: "feedbackData.htm?ratingId="+rating+"&msg="+msg,
async : false,
dataType: "html",
success: function(response) {
console.debug(response);
if(response == 'Y'){
$('#modal_window').html("<div id='message'></div>");
$('#message').html("<h2>Feedback Form Submitted!</h2>").append("<p>We will be in touch soon.</p>")
}
},
error : function(e) {
alert('Error: ' + e);
}
});
return false;
});
Try updating your ajax code by adding dataType : "html" so that it accepts response as string like below:
$.ajax({
type: "GET",
url: "feedbackData.htm?ratingId="+rating+"&msg="+msg,
dataType: "html",
success: function(response) {
console.debug(response);
if(response == 'Y'){
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/icon_pdf.png' />");
});
}
}
});
Also read jquery ajax official documentation for more clarification here

Ajax call not working in function

I have one function in java script. I want to send my form in ajax call after validation. I wrote ajax code for this but it's neither working nor giving any error on console even .
What can i do ?
javascript
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$.ajax({
type: "POST",
url: "quoteProcess.php",
data : $('#testform').serialize(),
success: function(data) {
alert(data);
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}

submit return false always in jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
this is my code here if(flag=="no") not working, the flag value is not changing, always it prevent default. is there any mistake in my code. ajax return are correct.
$(document).ready(function() {
$('#submit').click(function(event) {
var captcha = $("#captcha").val();
var flag = "no";
if (captcha == '') {
alert("Fill Captcha Field");
event.preventDefault();
} else {
var dataString = captcha;
$.ajax({
type: "POST",
url: "verify.php",
data: {
code: captcha
},
success: function(data) {
if (data == "no") {
alert("Invalid Captcha");
} else {
flag = "yes";
}
}
});
}
if (flag == "no") {
return false;
} else {
return true;
}
});
});
You can try this one, its working example.
var jqXHR = $.ajax({
url: "verify.php",
type: "POST",
data: {code: captcha},
async: false,
success: function (data) {
}
});
if(jqXHR.responseText=="no")
{
alert("Invalid Captcha");
}
else
{
flag="yes";
}
if(flag=="no")
{
return false;
}
else{
return true;
}
It will return after the successfully returning data from ajax request
By default javascript requests are sent asynchronously. when ajax is call take time to get response javascript execute next code. here in your code it is same issue. use below code
$(document).ready(function() {
$('#submit').click(function(event) {
var captcha = $("#captcha").val();
var response ;
if (captcha == '') {
alert("Fill Captcha Field");
event.preventDefault();
} else {
var dataString = captcha;
response = $.ajax({
type: "POST",
url: "verify.php",
data: {
code: captcha
},
success: function(data) {
}
}).responseText;
}
if (response == "no") {
alert("Invalid Captcha");
return false;
} else {
return true;
}
});
});

Function to impact a parent function

I have a function:
function validateForm() {
var result = ''
$.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if (data!=='') {
// make function validateForm return false
}
}
);
};
I would like to know if there is a way to do something in my condition that will apply to the function above the get request.
What I want to do exactly is that if my condition is met in my get request, then the function validateForm() return false.
Is there a way to accomplish that?
EDIT:
Here is what I tried
js:
var validateResult;
$('#but_id').click(function(event){
validateForm().done(function(){
if(!validateResult)
event.preventDefault();
});
})
function validateForm() {
var result = ''
return $.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if(data!==''){
validateResult = false;
}
}
);
};
html:
<form method="post" onsubmit="return validateForm();">
<input id='username' type="text" name="username"/>
<button type="submit" id='but_id'>Submit</button>
</form>
I assume you're trying to do something like this:
if (validateForm()) {
doSomething();
}
else {
displayError();
}
Instead, simply do this:
function validateForm(){
//...
$.get(
'/auth_validate_username/',
{ 'result': result },
success: function(data) {
doSomething();
},
error: function(data) {
displayError();
}
);
}
You just have to make sure that your server responds accordingly. I.e., your server shouldn't be generating a successful 200 response for every request to /auth_validate_username.
$.get is just a shorthand for $.ajax(). Read more about the callbacks in the docs.
Per your comment!
function doSomething(data, textStatus, jqXHR) {
$('form').submit();
}
function displayError(jqXHR, textStatus, errorThrown){ ... }
function validateForm(event){
$.ajax(
url: '/auth_validate_username/',
data: {"result": result},
success: doSomething,
error: displayError
);
return false; // prevent default form submit
}
$('form').submit(validateForm);
It would've been nice to know this was your goal from the start.
Use a sync call may implement what you want with 'async: false' when start a ajax call.
Tried in Chrome console and works.
function validateForm() {
var result = ''
var retval=true;
$.ajax(
'/auth_validate_username/',
{
async: false,
data: { 'result': result }
}
).done(function ( data ){
if(data !== ''){
retval = false;
}
});
return retval;
};
The ajax will complete after the function completes. So there is no way to do what you are looking for. Re-arrange your design or submit the form from the success function in the get.
Here is my crazy approach at a workaround
var validating = false;
var safeSubmit = false;
function validateForm()
{
validating = true;
$("#formElementId").ajaxStop(function () {
if( !validating ) return;
if( safeSubmit ) $(this).submit();
validating = false;
$(this).unbind("ajaxStop");
});
var result = ''
$.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if (data!=='') {
// make function validateForm return false
}else{
safeSubmit = true;
//this could also simply be
//$("#formElementId").submit();
}
}
);
return false;
}
Try using done with your function call.
In html
<input type ="button" id="yourButtonId" value="submit" />
In javascript
var validateResult;
$('#yourButtonId').click(function(event){
validateForm().done(function(){
//your code
if(!validateResult)
event.preventDefault();
});
})
function validateForm() {
var result = ''
return $.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if(data!==''){
// make function validateForm return false
validateResult = false;
}
}
);
};

How to make nested call with jquery

I've below code in JS file:
$(document).ready(function() {
$("#key_verify").click(function () {
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
if($.trim($("#key").val()).length != 0){
$.ajax({
type : "POST",
cache : false,
async : true,
url : "/issuekey?key="+$("#key").val(),
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj === undefined || json_obj == null){
}else{
if(json_obj.result == "true"){
top.location.href="/register"
}else{
$("#errrmsg").html(invalid_key);
}
}
},
error : function(data) {
$("#errrmsg").html(invalid_product_key);
}
});
}
});
}
How can I invoke above code in below lines so that when user hits enter key, it should make a call on enter key as well??
$("#key_verify").keypress(function(e) {
if(e.which == 13){
??????
}
});
Thanks!
Make the function you are passing to the click handler into a named function like so:
var verify = function(e) {
// your current anonymous function
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
// ... the rest of your function
}
Then pass it as an argument into your event handlers:
$("#key_verify").click( verify );
$("#key_verify").keypress(function(e) {
if(e.which == 13){
verify( e );
}
});

Categories