Ajax call not working in function - javascript

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

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

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

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