How to call two methods one by one in javascript? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Please have a look at this method. In this function response I am calling two functions findConnectedUsersRelationship() and displayUsers(response.users).
The problem is displayUsers(response.users) method runs and gets result before findConnectedUsersRelationship(). My requirement is I need to run first findConnectedUsersRelationship() and second displayUsers(response.users). Second method depends on first method.
function filterUsers(location, gender, youngAge, oldAge, interests){
var userId = signedUserId;
$.post(urlHolder.filter, {
userId: userId,
location: location,
gender: gender,
youngAge: youngAge,
oldAge: oldAge,
interests: interests
}, function(response) {
console.log('User response <<>>', response.users.length);
var filteredUsers;
findConnectedUsersRelationship();
displayUsers(response.users);
});
}
// To find connected user relationship
var relationshipList = new Array;
function findConnectedUsersRelationship() {
try {
$.post(urlHolder.findConnectedUsersRelationship, {
userId : signedUserId
}, function(response) {
//console.log('response downforanything: ', JSON.stringify(response));
if (response) {
for (var counter = 0; counter < response.users.length; counter++) {
relationshipList.push(response.users[counter].id);
}
} else {
console.log('No connected users >>>> ');
}
//console.log('relationshipList.length',relationshipList);
console.log('relationshipList length in auto complete *** ',relationshipList.length);
});
} catch (e) {
console.log('findConnectedUsersRelationship Exception >>>', e);
}
}

$.post returns a promise.
You can use this to continue your code:
function filterUsers(location, gender, youngAge, oldAge, interests){
$.post(url, { ... }, function(response) {
findConnectedUsersRelationship().done(function() {
displayUsers(response.users);
});
});
}
and change your findConnectedUsersRelationship() to return the promise from its ajax function,so instead of:
function findConnectedUsersRelationship() {
$.post(...
it becomes
function findConnectedUsersRelationship() {
return $.post(...

Related

Ajax multiple ajax request from online file [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 12 months ago.
function addIDS() {
const imdbIDs = [];
imdbIDs.push("id1");
imdbIDs.push("id2");
...
return imdbIDs ;
}
function getThemoviedbIDs(IDs) {
let arr = [];
let urls = [];
for(let i = 0; i < IDs.length; i++) {
urls.push(`...${imdb_ids[i]}...`);
}
$.each(urls, (i, u) => {
$(function() {
$.ajax({
url: u,
dataType: 'json',
success: function(data) {
arr.push(data.tv_results[0].id);
},
statusCode: {
404: function() {
alert('Err');
}
}
});
});
});
return arr;
}
function getDetails(themoviedbID) {
console.log(themoviedbID);
console.log(`...${themoviedbID[0]}`);
}
const imdbIDs = addIDS();
console.log("IMDB IDs: ", imdbIDs);
const themoviedbIDs = getThemoviedbIDs(imdbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
const themoviedbIDs = getThemoviedbIDs(themoviedbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
I am using themoviedb database.
populate() I add imdb IDs to the imdbIDs array, then I get themoviedb IDs by getThemoviedbIDs() function.
In the getDetails() function I would like to make ajax request just like in the getThemoviedbIDs() function, but unfortunatelly there is a problem in there. console.log(themoviedbID) output the appropriate array, but console.log(...${themoviedbID[0]}) output .../undefined...
I can get enough information about the series if I am using themoviedb ID.

ajax not setting value on declared variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have a problem with this javascript function. What I'm trying to do is, finding a specific "Material Description" using ajax call. When I try to console.log the ajax function, the data is showed up. But when I'm setting to an array, it won't set the array value and skipped. Using "async: false" give me this warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.
without async will give me undefined result.
$('#iBarcode').keypress(function (keyPressed) {
if (keyPressed.which == 13) {
var barcode = $('#iBarcode').val()
var splitted = new Array()
var arrayCnt = -1;
for (var i = 0; i < barcode.length; i++) {
var flagStart;
if (barcode.charAt(i) == ')') {
flagStart = true
i += 1
arrayCnt += 1
splitted[arrayCnt] = ''
}
if (barcode.charAt(i) == ('(')) {
flagStart = false
}
if (flagStart == true) {
splitted[arrayCnt] = splitted[arrayCnt] + barcode.charAt(i)
}
}
console.log(setMatDesc(splitted[0])) //value showed here
splitted[arrayCnt + 1] = setMatDesc(splitted[0]) //value not showed here and skipped?
splitted[arrayCnt + 1] = currentDate
$('#iBarcode').val('').focus
console.log(splitted)
}
})
function setMatDesc(MatID) {
var result
$.ajax({
url: '#Url.Action("Get_MatDesc")',
type: 'GET',
async: false,
data: { MatID: MatID },
success: function (data) {
result=data
},
error: function (xhr) {
alert('error');
}
})
return result
}
I would appreciate the help, thanks.
You need to provide a call back function which will get executed after ajax call completes like:
function setMatDesc(MatID, calback) {
var result
$.ajax({
url: '#Url.Action("Get_MatDesc")',
type: 'GET',
async: false,
data: { MatID: MatID },
success: function (data) {
callback(data); // note this
},
error: function (xhr) {
alert('error');
}
});
}
and at calling end do like:
setMatDesc(splitted[0],function(result) {
splitted = result;
splitted[arrayCnt + 1];
splitted[arrayCnt + 1] = currentDate;
});
The code might not work as i have not tested but this is the way to return the data from a function doing ajax call as the ajax call executes asynchronously and the function executes the body before the ajax call completes back from the server.

Javascript program not executing correctly

I'm new to javascript, but I can't get my head around this problem. I have a function that upvotes a game:
function upVoteGame(name) {
$.get("/get_gameValues", function(data) {
var alreadyExist = false;
var noVotes = false;
var games;
games = data;
for (var i = 0; i < games.length; i++) {
if (name === games[i].gameName) {
alreadyExist = true;
voteOperations();
if (userLoggedIn == false) {
alert("second");
swal("Cannot post votes", "Please log in or register to vote", "error");
}
if (noVotesLeft == false && userLoggedIn == true) {
$.ajax({
url: '/editVotes/' + games[i]._id,
type: 'PUT',
data: {
likes: games[i].likes + 1,
totalVotes: data[i].totalVotes + 1
},
success: function(result) {
alert(games[i].likes + 1);
}
});
}
refreshGameValues();
break;
}
}
//This is for us Developers!
if (!alreadyExist) {
$.post("/add_game_to_dB", {
gameName: name
}, function(result) {
alert("Introduced " + name);
});
}
});
}
Now I have the function that updates the user's votes left, voteOperations():
function voteOperations() {
$.get("/users/get_current_user", function(data) {
//var votes = 5;
for (var i = 0; i < data.length; i++) {
votesRemaining = data[i].votesRemaining;
userLoggedIn = true;
alert("votes left : " + votesRemaining);
if ((votesRemaining - 1) < 0) {
swal("No votes remaining", "Please wait 24 hours to get more votes", "error");
noVotesLeft = true;
}
if (noVotesLeft == false) {
$.ajax({
url: '/users/updateUserDetails/' + data[i].user_name,
type: 'PUT',
data: {
votesRemaining: votesRemaining - 1
},
success: function(result) {}
});
}
}
});
}
My problem is a simple problem. In the upVoteGame(name) function, I want the voteOperations() to execute before the if loop below it. However, when I run the code, the if loop below executes first and alerts the user that they are not logged in. When a user logs in, userLoggedIn is set to true, but the if loop executes firsts and tells them that they are not logged in, and then executes the voteOperations() function. I don't know why this is happening. How can I fix this so that voteOperations executes before the if loop?
This is because the voteoperations function has a get request which is asynchronous. You will need a callback function where you should include if condition
You can try:
function upVoteGame(name) {
vote(afterGet);
}
afterGet() {
if condition here
}
function vote(callback) {
$.get .... {
//after getting data
callback();
}
}
You problem occurs due to the asynchronous call of your $.get in the voteOperations function.
Since it is an asynchronous call your code continuous while your $.get is waiting to retrieve data and thus your if statement seems to trigger before your voteOperations function.
In simple words your function actually is triggered before the if statement but before it completes it's result the code continues and triggers your if statement.
You could put your if statement (logic) in the success callback of your vote operation function or use $.ajax with async:false which is not considered a good practice generally but I use it sometimes.
Something like that for example (for the second case)
$.ajax({
async: false,
.....
success: function (response) {
//
}
});
Asynchronous calls can be handled with jquery function Deffered
function upVoteGame(name) {
vote().then(doUpVoteGame(), handleError());
}
function doUpVoteGame() {
...
}
function handleError(e) {
console.error("fail", e);
}
function vote() {
var d = new $.Deferred();
$.get .... {
d.resolve();
}).fail(function(e) {
d.reject(e);
});
return d;
}

How do I get value from Ajax function for jquery onclick function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a button that when I click on it , it will get data from my database , and display it on my text area based on the id.
JQuery
$('#verifyBtn').on("click", function() {
var exeOutput = checkOutput();
$("outputArea").html(exeOutput);
});
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
function getOutput(dataStr, flag) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
return data;
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
Through my servlet for getting from my database.
Servlet
exercisesModel outputModel = null;
try {
DBConnection db = new DBConnection();
outputModel = db.getExerciseById(request.getParameter("exNo"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().append(outputModel.getExpOutput());
EDIT: Upon clicking, i think there is data but my text area is not displaying it.
Since you're making an Asynchronous call you can't return an immediate response using return data;, but instead you could pass the selector then assign the result to your output element when the success callback is called:
<script>
$('#verifyBtn').on("click", function() {
checkOutput("outputArea");
});
function checkOutput(output_selector){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true, output_selector);
}
function getOutput(dataStr, flag, output_selector) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
$(output_selector).html( data );
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
</script>
NOTE : The passed flag parameter isn't used.
Hope this helps.
This block here:
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
try adding a return to the getOutput line
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
return getOutput(dataString, true);
}
By value i guess you mean the result of the call. You can find that in the parameter of the success handler.
success: function (data) {
//This is your result from server.
console.log(data);
return data;
}
Take a look at your JS console to see the results.

Javascript "push" into array not working (Facebook app)

I am trying to store my friends list (name, picture and gender) on a var, but it doesn't work correctly. Please ready the comments in the code for the details. Any ideas? Thanks.
function getFriendsArray() {
var friendsArray = [];
FB.api('/me/friends?fields=name,picture,gender', function(response) {
if(response.data) {
var data = '';
$.each(response.data, function(indice, item) {
alert(item.name); // Friend's name are displayed correctly
friendsArray.push(item); // I believe this doesn't work
});
}
else {
errorHandler('getFriendsArray', JSON.stringify(response));
}
});
alert(friendsArray.length); // Returns 0 (incorrect)
return friendsArray.sort(sortByName);
}
The call function(response) is asynchronous. You should insert the alert after $.each
for completeness: you should change your approach to problem: do not call a function that returns an Array but that call a second function.
function getFriendsArray(callback, errorHandler) {
var friendsArray = [];
FB.api('/me/friends?fields=name,picture,gender', function(response) {
if(response.data) {
var data = '';
$.each(response.data, function(indice, item) {
alert(item.name); // Friend's name are displayed correctly
friendsArray.push(item); // I believe this doesn't work
});
callback(friendsArray);
}
else {
errorHandler('getFriendsArray', JSON.stringify(response));
}
});
}
getFriendsArray(function(friends) {
alert(friends);
},
function(error) {
alert('error');
});
It looks like the FB.api makes an asynchronous request (like jQuery.ajax) and so you are executing alert(friendsArray.length) before the FB.api call completes and pushes the results into the friends array.

Categories