submit return false always in jquery [duplicate] - javascript

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;
}
});
});

Related

Javascript validation works...and fails

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>

How do I make a function run and finish before a loop starts in JS

I've got a JS file that's automatically run through an HTML script. I want the console to print out "changing to true" before it prints out "starting toggle". The reason for this is because I want the function to call an API and change the toggle "checked" states before it loads. How do I do this?
$(document).ready(function(){
for (var i=0;i<Object.keys(obj).length;i++) {
var obj_name = Object.keys(obj)[i];
obj_id = "#"+obj_name;
$(obj_id).bootstrapToggle();
console.log("starting toggle")
}
})
$("#samplekey").ready(function() {
checkKey("#samplekey", power_toggles["samplekey"]);
})
function checkKey(obj_id, url1){
var http_verb = "GET";
$.ajax({
url: url1,
type: http_verb
}).done(function(data) {
if (data == 1234) {
$(obj_id).prop("checked", true);
console.log("changing to true")
}
else
{
$(obj_id).prop("checked", false);
}
}).fail(function(data,textStatus,errorThrown) {
alert(errorThrown);
});
}
You could made this change in your code:
$(document).ready(function() {
checkKey("#someUrl", "someUrl")
})
function checkKey(obj_id, url1) {
var http_verb = "GET";
$.ajax({
url: url1,
type: http_verb
}).done(function(data) {
for (var i = 0; i < Object.keys(obj).length; i++) {
var obj_name = Object.keys(obj)[i];
obj_id = "#" + obj_name;
$(obj_id).bootstrapToggle();
console.log("starting toggle")
}
if (data == 1234) {
$(obj_id).prop("checked", true);
console.log("changing to true")
} else {
$(obj_id).prop("checked", false);
}
}).fail(function(data, textStatus, errorThrown) {
alert(errorThrown);
});
}
$("#samplekey").ready(function() {
checkPOEPower("#samplekey", power_toggles["samplekey"]);
})
And remember that Javascript is Asynchronous, this means that the code never stops for external requests or others events.
You should make the ajax request sync. Add a property "async: false" in your codes
$.ajax({
url: url1,
type: http_verb,
async: false
}).done(function(data) {
if (data == 1234) {
$(obj_id).prop("checked", true);
console.log("changing to true")
}
else
{
$(obj_id).prop("checked", false);
}
}).fail(function(data,textStatus,errorThrown) {
alert(errorThrown);
});

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();
}
}
}

JavaScript Validation error?

I have been working on a JavaScript validator, but for some reason, evalid always returns as false even if it has passed validation... this is a bug as if evalid is false, the form doesn't submit.
function signup_validate()
{
document.getElementById("email_error").innerHTML = "";
document.getElementById("password_error").innerHTML = "";
evalid = false;
pvalid = false;
email = null;
pass = null;
confpass = null;
email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
atpos=email.indexOf("#");
dotpos=email.lastIndexOf(".");
pass=document.forms["signup_form"]["pass"].value;
confpass=document.forms["signup_form"]["confpass"].value;
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
}
else
{
$.post('/resources/forms/signup.php',{email: email}, function(data){
if(data.exists){
document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
}
else
{
evalid = true;
}
}, 'JSON');
}
if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
{
pvalid = true;
}
else
{
document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
}
alert(evalid);
if (evalid == true && pvalid == true)
{
document.getElementById("signup_form").submit();
}
else
{
return false;
}
}
What could I have missed?
The only moment when you set "evalid" true is inside a function that runs asynchronously. In other words, by the time you set "evalid" true the main function has already reached the end.
You Could try to use $.ajax instead of $.post and use the parameter async:false
Try something like this:
$.ajax({
type: 'POST',
url: '/resources/forms/signup.php',
data: {email: email},
success: function(response){
//your function here
},
dataType:'JSON',
async:false
});

Categories