javascript validation and ajax call simultaneously not working - javascript

I have code in that javascript and ajax call need to be work simultaneously. But it did not work. And always go to return true.
Functionality of create function is validation of data and ajax call which execute query and depend on result it will further execute. If response text is yes then it call confirmval function. And then further it ask for confirmation and next execution But I face problem is function not return false it always go to true. I cant understand why this happening?
function create()
{
if (document.companyregister.cmpname.value === "")
{
alert("Please Enter Company name");
document.companyregister.cmpname.value = "";
document.companyregister.cmpname.focus();
return false;
}
var companyname = document.companyregister.cmpname.value;
var username = document.companyregister.username.value;
$.ajax({
url: 'checkexisting.php',
type: 'POST',
data: {companyname: companyname,username:username},
success: function(errorResponse) {
var result = errorResponse.trim();
if(result=="yes"){
return confirmval(companyname,username);
}
else{
document.getElementById("formsubmitting").style.display = "block";
document.getElementById("hidesubmit").style.display = "none";
return true;
}
}
});
}
function confirmval(companyname,username){
var c = confirm("This company is already created.\nWould you like to delete existing company?");
if(c){
alert("c");
$.ajax({
url: 'updatecompany.php',
type: 'POST',
data: {companyname: companyname,username:username},
success: function(responsetext) {
var result = responsetext.trim();
if(result=="yes"){
document.getElementById("formsubmitting").style.display = "block";
document.getElementById("hidesubmit").style.display = "none";
return true;
}
}
});
}
else{
alert("notc");
window.location="http://www.google.com";
}
}

You are trying to return two values after your first ajax call:
if(result=="yes"){
return confirmval(companyname,username);
return false;
}
This will just return the result of confirmval function (which appears to always return true), and the 'return false' line will never be run, thus it will always return true.
If you need that result=="yes" to return false, I might recommend something like:
if(result=="yes"){
var confirmvalResult = confirmval(companyname,username);
if(confirmvalResult) {
return false;
} else {
// not sure what you want to do here
}
}

Related

Wait for AJAX response before moving on with script

I have a script which runs 2 AJAX calls, the first checks that a record exists within a database. If it does this should not move on and the script should stop. The second submits a job.
My problem is that the job is being submitted before the first AJAX call has returned. My code looks something like this:
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function( data ){
if (data.Response == "Success") {
var noresults = data.Results;
if (noresults > 0){
alert('this record id already exists!');
return false;
}
} else {
alert('an error occured');
return false;
}
}
});
} else {
alert('enter a record id');
return false;
}
// second ajax call goes here, which gets called regardless of the output of the ajax call above
Instead of putting the call to the second ajax method at the bottom of your code (where the comments currently are), put it in the "success" function of your first call. This method will only execute once the first call has finished. This is the only way to ensure that the second call does not happen too early. Ajax calls run asynchronously, so the normal flow of the browser is not interrupted. This is deliberate so that long-running calls don't lock up the browser for the user.
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function(data) {
//check here if you want to call submitJob or not
//and call submitJob()
}
});
} else {
alert('enter a record id');
return false;
}
//call this ajax once you varified your condition from success callback of first one
function submitJob() {
//second ajax call goes here
}
You have to use jquery promise function for that which will wait for the first ajax request to complete then make another ajax request.
JQUERY PROMISE
OR
Put the second ajax request in the success function of first one, and make it happen when you want it to fire
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function(data) {
//check here if you want to call submitJob or not
if (noresults > 0){ return false }
else { Job(); };
}
});
} else {
alert('enter a record id');
return false;
}
function Job() {
//another ajax call.
}
Hope it helps :)
try this: make async propety false
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
async : false, //added this
success: function( data ){
if (data.Response == "Success") {
var noresults = data.Results;
if (noresults > 0){
alert('this record id already exists!');
return false;
}
} else {
alert('an error occured');
return false;
}
}
});
} else {
alert('enter a record id');
return false;
}
OR
perform second ajax call in success function of first ajax call i.e. see comment
if (recordid) {
var request = $.ajax({
context: document.body,
url: URLGOESHERE,
data: {
recordID: recordid
},
success: function( data ){
if (data.Response == "Success") {
var noresults = data.Results;
if (noresults > 0){
alert('this record id already exists!');
return false;
}
//perform 2nd ajax call here
} else {
alert('an error occured');
return false;
}
}
});
} else {
alert('enter a record id');
return false;
}

how do i wait for multiple ajax calls to complete from a .each loop

I am running a loop that updates records on a table but i need to wait for all of the records to update before i continue on.
How can I have jquery wait until all of the calls in the loopselectedrows function completes? I have read about .deferred and .when but i am not sure how to implement
either. they both do not seem to able to handle an array of calls if i where to change over to using an array for the ajax posts. Any help would be greatly appreciated.
this is the button that starts it all :
click: function () {
// validate all rows
var $selectedRows = $('#Table1').jtable('selectedRows');
LoopSelectedRows($selectedRows, 'Validate');
/// wait here until all ajax calls have completed
// then continue with checking
// check for any row with an error
var $ValidatedRows = $('#Table1').jtable('selectedRows');
var boolCheck = checkValidatedRows($ValidatedRows);
// if all records are succesfull then add them
// else alert user
if (boolCheck == true) {
LoopSelectedRows($selectedRows, 'Add');
}
else {
alert("Please correct invalid records and try again");
}
}
the first thing this does is take all of the records from the table and passes them to a looping function.
this is the looping function -
function LoopSelectedRows(SelectedRecords, actionType) {
if (SelectedRecords.length > 0) {
//Show selected rows
SelectedRecords.each(function () {
var record = $(this).data('record');
record.PERSON_NAME = record.PERSON_ID;
// Actions for loop
// Validation Action
if (actionType == 'Validate') {
check = validateRecord(record);
}
// call add function
if (actionType == 'Add') {
AddRecordToTable(record);
}
})
};
}
this loop can either validate or add records for now i am only worried about the validation function
this is the validation function:
function validateRecord(dataRecord) {
$.ajax({
url: "./ValidateAddRecord",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(dataRecord),
success: function (data) {
if (data.Result == "OK") {
// update record with message
$('#table1').jtable('updateRecord', { record: data.Record });
}
else {
// display error
alert(data.Message);
}
}
});
}
One fairly clean way to know when multiple ajax calls are done is to use promises and jQuery's $.when(). That will give you a callback when all the ajax calls are done. It will take a little bit of reorganization of your code to use that.
First, you return the $.ajax() promise from validateRecord():
function validateRecord(dataRecord) {
return $.ajax({
url: "./ValidateAddRecord",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(dataRecord),
success: function (data) {
if (data.Result == "OK") {
// update record with message
$('#table1').jtable('updateRecord', { record: data.Record });
}
else {
// display error
alert(data.Message);
}
}
});
}
Then, you collect all the promises in LoopSelectedRows() and return a master promise using `$.when():
function LoopSelectedRows(SelectedRecords, actionType) {
var promises = [];
if (SelectedRecords.length > 0) {
//Show selected rows
SelectedRecords.each(function () {
var record = $(this).data('record');
record.PERSON_NAME = record.PERSON_ID;
// Actions for loop
// Validation Action
if (actionType == 'Validate') {
promises.push(validateRecord(record));
}
// call add function
if (actionType == 'Add') {
promises.push(AddRecordToTable(record));
}
})
};
// return master promise
return $.when.apply($, promises);
}
Then, you can use that final promise to know when everything is done.
click: function () {
// validate all rows
var $selectedRows = $('#Table1').jtable('selectedRows');
LoopSelectedRows($selectedRows, 'Validate').then(function() {
// all the ajax calls in LoopSelectRows are done now
// check for any row with an error
var $ValidatedRows = $('#Table1').jtable('selectedRows');
var boolCheck = checkValidatedRows($ValidatedRows);
// if all records are succesfull then add them
// else alert user
if (boolCheck == true) {
LoopSelectedRows($selectedRows, 'Add');
} else {
alert("Please correct invalid records and try again");
}
});
FYI, you probably also want to change AddRecordToTable() to return a promise so it can work the same way (though it is not required because you aren't trying to wait for that operation to be done).
$.active returns the number of active Ajax requests. Use $.active==0 means no ajax requests are active. You could also use ajaxStart and ajaxStop to keep track of when requests are active.
Thank you jfriend00, your solution seems to have solved my issues.
Below is the updated version i am now using for anyone interested :
click: function () {
// validate all rows
var $selectedRows = $('#table1).jtable('selectedRows');
LoopSelectedRows($selectedRows, 'Validate').then(function () {
// check for any row with an error
var $ValidatedRows = $('#table1).jtable('selectedRows');
var boolCheck = checkValidatedRows($ValidatedRows);
// if all records are succesfull then add them
// else alert user
if (boolCheck == true) {
LoopSelectedRows($selectedRows, 'Add');
}
else {
alert("Please correct invalid records and try again");
}
});
}
// loop function
function LoopSelectedRows(SelectedRecords, actionType) {
var promises = [];
if (SelectedRecords.length > 0) {
//Show selected rows
SelectedRecords.each(function () {
var record = $(this).data('record');
// Actions for loop
// Validation Action
if (actionType == 'Validate') {
promises.push(validaterecord(record));
}
// call add function
if (actionType == 'Add') {
AddRecordToTable(record);
}
})
};
return $.when.apply($, promises);
}
// validate function
function validaterecord(dataRecord) {
var def = $.Deferred();
$.ajax({
url: "./ValidateAddRecord",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(dataRecord),
success: function (data) {
if (data.Result == "OK") {
// update record with message
$('#table1).jtable('updateRecord', { record: data.Record });
// resolve token
def.resolve();
}
else {
// display error
alert(data.Message);
}
}
});
return def.promise();
}

AJAX "success" executing before response is returned

I'm hoping this is just a simple fix due to me being a little dumb somewhere along the line. I'm executing my ASP.NET MVC login using AJAX. There is a "success" handler which returns a "true" value to the calling function which, in turn, load the home page.
The issue is that the "success" handler is executing BEFORE any value is returned - which means that nothing happens because the value is not "SUCCESS". I can confirm this by looking at the request in Firebug, the value returned is SUCCESS but nothing happens. If I apply a breakpoint to the end of the function and then continue execution it works just fine.
I have no idea what the issue is, I'd be very grateful for help or an explanation to what I'm doing wrong.
Thanks!
My JS Function:
function LogIn(UserName, Password) {
var Cont = true;
var ErrorString = "";
if (UserName == null || UserName == "") {
Cont = false;
ErrorString += "Username is Required.";
}
if (Password == null || Password == "") {
Cont = false;
ErrorString += "Password is Required.";
}
var result = false;
if (Cont) {
var LogInUrl = "/AJAX/LogIn?UserName=" + UserName + "&Password=" + Password;
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
result = true;
}
}
})
}
return result;
}
UPDATE: The function that calls the LogIn function:
$('#FormLogin').submit(function (e) {
e.preventDefault();
var UserName = $("#TxtLoginUsername").val();
var Password = $("#TxtLoginPassword").val();
var IsLoggedIn = LogIn(UserName, Password);
if (IsLoggedIn) {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
})
As I said, the function does it's job and logs me in, but the "success" handler seems to execute before the value is returned.
Change your ajax call to something like this:
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
}
});
There is no point in returning result from LogIn, it'll always be false. You need to put the code handling the returned value in the callback.
Another alternative, if you don't like the idea of your LogIn function being so closely coupled to DOM manipulation is to return the promise from your ajax call. So at the end of LogIn, you'd do something like this:
return $.ajax({
url: LogInUrl,
type:"GET"
}
});
And then when you call it, you'd do something like this:
LogIn(UserName, Password).then(function(data) {
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
});

how to break execution and display error inside success of ajax?

I am using ajax call to check for some validation and then submitting the form normally by html. In my ajax call,
function checkId() {
var str = $("#formObj").serialize();
$.ajax({
type : "post",
data : str,
url : "checkForId.mt",
async : false,
success : function(txt) {
if (txt == "pass") {
return "true";
} else if (txt == "same") {
$("#errorMsgIdSame").removeClass("hidden");
return "false";
}
},
error : function() {
alert("Error");
}
});
}
If the control goes to "pass", execution should continue. If it goes to "same", the execution should stop.
I am calling this ajax method from some other method.
function validateForm() {
var isValid = true;
isValid = checkId();
if (!isValid) {
$("#errorMsg").removeClass("hidden");
}
return isValid;
}
this validatioForm is called on button click. Now ajax code is working but validateForm method is not taking the return of the ajax method.
Need direction on how to carry this out so that to capture the return from the ajax method and how to return from the ajax method.
If I understood your question correctly, you want to return the result of an inner function from an outer function. This definition of checkId does just that.
function checkId() {
var result;
var str = $("#formObj").serialize();
$.ajax({
type : "post",
data : str,
url : "checkForId.mt",
async : false,
success : function(txt) {
if (txt == "pass") {
result = true;
return;
} else if (txt == "same") {
$("#errorMsgIdSame").removeClass("hidden");
result = false;
return;
}
},
error : function() {
alert("Error");
}
});
return result;
}
An ajax call is asynchronous.
When you call ajax what is happening is that the ajax starts a new thread to do its task--a post in your case.
After that the code that called the ajax keeps going.
When the task that the ajax call is doing returns, it executes what ever is in its pass or fail sections depending on the task status.
So basically your checkId method completes and returns before the ajax is finished.
I would recommend triggering whatever you need the return value for from the success section or fail section like this:
success : function(txt) {
if (txt == "pass") {
newfunction(true);
} else if (txt == "same") {
$("#errorMsgIdSame").removeClass("hidden");
newfunction(false);
}
},
Edit:
function newfunction(passFail)
{
//Do something with variable passFail
}

calling jquery ajax function from javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery ajax return value
How to return the response from an AJAX call from a function?
I have javascript. It loads data from database. I want to return true or false with respect to loading data. But I could not return it. My code has given bellow:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.get(url, {
isrc: isrc
}, function (data) {
if (data == "true") {
result = true;
}
else {
result = false;
}
});
return result;
}
It always gives false result. Anyone has faced this kind of problem? 'Thanks advance'
If it's so important to use the function synchronously you can refactor it to:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.ajax({
async: false,
success: function (data) {
if (data == "true") {
result = true;
}
else {
result = false;
}
},
data: { isrc: isrc }
});
return result;
}
As #ManseUK async is deprecated in jQuery 1.8 so if you want synchronous approach you should use older version.
The problem is that when you return result, It doesnt have value. because the ajax didn't finish its task. you make some callback function and when the result of ajax is returned from server, do what you want to.
Some thing like this:
function CheckISRC(Callback) {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.get(url, {
isrc: isrc
}, function (data) {
if (data == "true") {
Callback(true);
}
else {
Callback(false);
}
});
}
function YourCallback(result) {
//...
}
The JQuery ajax functions are asynchronous. This means that when you initialise result to false, the result is set to true or false after the "return result;" line has run.
You can make the call synchronous but this is considered worse practice. You are often better off refactoring your code to allow for the asynchronous nature of the JQuery Ajax.
For example, where you previously had:
function myFunction() {
//Code before
var result = CheckISRC();
//Code after using result
}
you could have the following:
function myFunction() {
//Code before
CheckISRC();
}
function myFunction_callback(result) {
//Code after using result
}
where you call myFunction_callback in the success option of your ajax code like so:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
$.get(url, {
isrc: isrc
}, function (data) {
myFunction_callback(data == "true");
});
}

Categories