JQuery Timing with the load() - javascript

I am currently trying to make a tool for my work and the timing is messing me up a lot. Hopefully someone can help here. Below is my code that I currently have. The issue is when I grab a selected item and run the $("#JJ_HOLDER").load(), it is sometimes not waiting to finish. I need everything to finish in the callback function THEN run the submitTaskbyHolder() but only when it is complete. Any and all help is appreciated!
End Goal: Run RunCad() and have it load data into $("#JJ_HOLDER") then run submitTaskbyHolder() then empty and repeat with another data set (parseInt(selected[i]))
function submitTaskbyHolder(){
var loginUser = $("#hdnUserID").data('value');
$.ajax({
type: "POST",
url: app.global.AppPath + 'WorkRequestDetails/SubmitWorkRequestDetails/',
data: $('#FormID').serialize(),
dataType: 'json',
success: function (result) {
if (result.Status == "Show Add Module") {
app.workRequestDetails.OpenWorkRequestDetailsPopup("Submit");
}
else {
if (result.Status == "Module submitted.") {
if (result.ModuleAndStatus.CurrentAssignedId == loginUser) {
app.modalPopup.isCancel = false;
$("#BTNStop").click();
app.workRequestDetails.display_notifyresultA("Successfully submitted work request.");
$('#HFCurrentModuleID').val(result.ModuleAndStatus.ModuleId);
$('#HFCurrentStatusID').val(result.ModuleAndStatus.StatusId);
$('#txtModule').val(result.ModuleAndStatus.ModuleName);
$('#txtStatus').val(result.ModuleAndStatus.StatusName);
console.log('submitted');
}
else {
app.modalPopup.isCancel = false;
app.layoutdash.display_notifyresult("Successfully submitted work request.");
console.log('submitted');
}
}
else {
swal(result.Status);
}
}
},
error: function (result) {
swal(result.Status);
}
});
}
var i = 0;
function RunCad() {
selected = app.dashboardGridview.selectedItems;
if(selected.length == 0){
swal({title: "Error",
text: "Ensure there is more than one selected!",
icon: "error",
button: "Okay",
});
}else{
setTimeout(function () {
$("#JJ_HOLDER").empty();
$("#JJ_HOLDER").load(app.global.AppPath + 'WorkRequestDetails/GetWorkRequestDetails/', { projectID: parseInt(selected[i]) },function() {
$(body).css('padding-right', '0px');
app.addWorkRequest.LoadTooltipsterToPopup();
app.multiSelectSettings.MultiSelectSettings();
app.modalPopup.Loadfunctions('WorkRequestDetails/GetWorkRequestDetails/');
app.modalPopup.FixTabPressModalPopup();
submitTaskbyHolder();
console.log(selected[i] + ' is complete!');
});
i++;
if (i+1 < app.dashboardGridview.selectedItems.length) {
RunCad();
}else{
app.modalPopup.ReloadDashboardView();
}
}, 3000)
}
}

Related

How to check ajax/php response async? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 months ago.
this code doesn't work, because it always return undefined. In my opinion the "success" from the ajax should return, if the result is there.
How to make sure, that the boolean will be returned?
<script>
$('#sbtn').on("click", function(e) {
e.preventDefault();
// if user exists, set validated to true
var validated = checkUser('requestedUser');
// if the user is validated, submit form
if(validated) {
//alert("Thank You");
$('#setup').submit();
}
}
function checkUser(user) {
data = {
lernsax_email: user
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: data,
success: function(msg){
if(msg === "passed") {
// php returns "passed", if the user can be found
console.log(msg);
return true;
} else {
console.log(msg);
return false;
}
},
});
}
</script>
you can use Promise
<script>
$('#sbtn').on("click", function(e) {
e.preventDefault();
// if user exists, set validated to true
let result = checkUser('requestedUser');
result.then(validated => {
if(validated) {
//alert("Thank You");
$('#setup').submit();
}
});
}
function checkUser(user) {
data = {
lernsax_email: user
}
return new Promise(resolve => {
$.ajax({
type: "POST",
url: "checkuser.php",
data: data,
success: function(msg){
if(msg === "passed") {
// php returns "passed", if the user can be found
console.log(msg);
resolve(true);
} else {
console.log(msg);
resolve(false);
}
},
});
});
}
</script>
or move
if(validated) {
//alert("Thank You");
$('#setup').submit();
}
to success funtion of ajax
<script>
$('#sbtn').on("click", function(e) {
e.preventDefault();
// if user exists, set validated to true
checkUser('requestedUser');
}
function checkUser(user) {
data = {
lernsax_email: user
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: data,
success: function(msg){
if(msg === "passed") {
// php returns "passed", if the user can be found
console.log(msg);
$('#setup').submit();
return true;
} else {
console.log(msg);
return false;
}
},
});
}
</script>

How to repeat ajax request depending return

I have this code :
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
});
I want if data == 0 need to make another call on app_auction_end after 10 sec. Can you help me please ? Thx in advance and sorry for my english
Give the operation a named function:
var someFunction = function () {
$.ajax({
//...
});
};
Which you would then use for your .on() call:
.on('finish.countdown', someFunction)
And in the success handler, set a timeout for that function:
if (data == 0) {
setTimeout(someFunction, i_timer);
}
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
//do our initial call otherwise it will never get called.
onEndAuction();
});

Why is my AJAX running 4 times

http://i.imgur.com/eFjV8Uv.png
$("#login").on('click', function () {
$(".login .col2, .login .signin, .login .close").fadeOut(500, function () {
$(".login .spinner").fadeIn(500);
var username = $("#username").val();
var password = $("#pw").val();
var data = "username="+username+"&password="+password;
$.ajax({
url: './api/prijava',
method: 'POST',
data: data,
dataType: 'json',
success: function(data) {
if(data.odg == 1) {
$(".login .spinner").fadeOut(500, function() {
$(".login .msg").append('Prijava uspješna').fadeIn(500, function() {
window.location = "./";
});
});
} else if(data.odg == 2) {
$(".login .msg").css('background-color', 'rgba(0, 255, 0, 0.5)').append('<span>Prijava uspješna! Dobrodošli...</span>').fadeIn(500, function() {
window.location = "./?first=true";
});
}
},
error: function(err) {
console.log(err);
}
});
});
});
Screenshot shows successful login (local language) but it should show it once, rather than 4 times. How can I make it load once and that's it?
The callback to fadeOut will run once per selected element. Instead you could use the promise to since when it resolves it only runs once:
$(selector).fadeOut(500).promise().then(function () {
// do ajax call here
});

AJAX call never reaching error statement

In the AJAX call below, I am attempting to debug the JavaScript call to understand why I cannot get to the error block when checking for failures. Whenever I debug in Chrome Developer tools, it jumps to the last line of the function and not the error block. Is there a easier way to test why this isn't being hit?
$("#input-userName").blur(function () {
var userNameTxt = $("#input-userName").val();
if (userNameTxt != prevUserName) {
if (userNameTxt.length >= 6 && userNameTxt.length <= 20) {
$("#divVerifyUserName").show();
$("#input-userName").prop("disabled", true);
$.ajax
({
type: "GET",
url: BASE_URL + "MyCall",
async: true,
data: { 'userName': userNameTxt },
success: function (resultset) {
prevUserName = userNameTxt
$("#userNameValidationMessage").removeClass("error");
if (resultset != null) {
$("#divVerifyUserName").hide();
$("#input-userName").prop("disabled", false);
if (resultset.status) {
$("#userNameValidationMessage").addClass("message");
}
else {
$("#userNameValidationMessage").removeClass("message");
$("#userNameValidationMessage").addClass("error");
}
$("#userNameValidationMessage").text(resultset.msg);
}
},
error: function (xhr, error) {
$("#userNameValidationMessage").text("Error while processing the request. Please try again.");
}
});
}
}
});

how to stop one method execution untill another method completes in javascript with Linkedin API people search?

I am calling IN.API.PeopleSearch() from a for loop, and this for loop is in ajax success method, but before completing for loop execution, ajax method complete is getting called.
I want to stop until the for loop completes.
$.ajax({
type: 'GET',
dataType: 'json',
url: "get_data.htm",
async : false,
success: function(data, textStatus ){
for(i in data){
searchClick(data[i].firstName,data[i].lastName);
}
alert(resultArray);//here i want to send the response to server side
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
here is my searchClick function :
function searchClick(firstName, secondName) {
if (!IN.ENV.auth.oauth_token) {
alert("You must login w/ LinkedIn to use the Search functionality!");
return;
}
IN.API.PeopleSearch()
.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",
"summary","numConnections")
.params({
"first-name": firstName,
"last-name": secondName
})
.result(function(result, metadata) {
for (i in result.people.values) {
try{
resultArray[i] = result.people.values[i];
}catch(err){
alert(err);
}
}
});
}
alert(resultArray) is getting called before completion of for loop, how to handle this.
I don't know if I get your question, but maybe something like that works for you: (not tested)
var Queue = function(callback) {
this.count = 0;
this.done = 0;
this.callback = callback;
};
Queue.prototype.oneDone = function() {
if (++this.done == this.count) {
this.callback();
}
}
Queue.prototype.process = function(data, callback) {
this.count = data.length;
for (i in data ) {
callback(data[i], this);
}
};
$.ajax({
type: 'GET',
dataType: 'json',
url: "get_data.htm",
async : false,
success: function(data, textStatus) {
var myQueue = new Queue(function() {
alert(resultArray); //here i want to send the response to server side
});
myQueue.process(data, function(item, queue) {
searchClick(item.firstName, item.lastName, queue);
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
function searchClick(firstName, secondName, queue) {
if (!IN.ENV.auth.oauth_token) {
alert("You must login w/ LinkedIn to use the Search functionality!");
return;
}
IN.API.PeopleSearch()
.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",
"summary","numConnections")
.params({
"first-name": firstName,
"last-name": secondName
})
.result(function(result, metadata) {
for (i in result.people.values) {
try {
resultArray[i] = result.people.values[i];
} catch(err) {
alert(err);
}
}
if (queue) {
queue.oneDone();
}
});
}
I don't know what you are doing exactly, but can say we have one method, async
Function.prototype.async = function () {
setTimeout.bind(null, this, 0).apply(null, arguments);
};
This allows me to write code like this:
alert.async("This will be displayed later.");
alert("This will be displayed first.");
so the code with .async will called once the other event is completed.
Else in your case, use
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
for checking if the document is ready then send /fill /success. this is Raw AJAX method. :)
O hope this may help :)

Categories