Answer the question
In order to leave comments, you need to log in
How to get return from ajax request?
Good day to all. I have the following click event:
$('.post-like').click(function(){
var item_id = $(this).parents('.item').attr('id');
var isVoted = false;
//проверяем что пользователь уже проголосовал
already_vote(item_id, isVoted);
if(isVoted){
//...
}
else{
//...
}
});
function already_vote(post_id, isVoted){
$.ajax({
url: '/ajax/post_like.php',
type: 'POST',
dataType: "json",
data: {
action: 'check',
post_id: post_id
},
})
.done(function(response){
if(response.already_vote == 1){
isVoted = true;
}
})
.fail(function(xhr){
console.log(xhr);
});
}
Answer the question
In order to leave comments, you need to log in
Everything you wrote is correct. Either pass the callback to the already_vote function , or do it via a promise.
Callback option:
function already_vote(post_id, callback){
$.ajax({ <options> })
.done(function(response){
if(response.already_vote == 1){
return callback(true);
}
return callback(false);
})
.fail(function(xhr){
console.log(xhr);
});
}
$('.post-like').click(function(){
const item_id = $(this).parents('.item').attr('id');
already_vote(item_id, function(isVoted) {
if(isVoted){
//...
}
else {
//...
}
});
});
function already_vote(post_id, callback){
return new Promise(res => {
$.ajax({ <options> })
.done(function(response){
if(response.already_vote == 1){
return res(true);
}
return res(false);
})
});
}
$('.post-like').click(async function(){
const item_id = $(this).parents('.item').attr('id');
const isVoted = await already_vote(item_id);
if(isVoted){
//...
}
else {
//...
}
});
Use async / await - this is the easiest and most convenient way.
Example:
$('.post-like').click(async function(){
var response = await $.ajax({
url: '/ajax/post_like.php',
type: 'POST',
dataType: 'json',
data: {
action: 'check',
post_id: $(this).parents('.item').attr('id')
}
});
if (response.already_vote == 1) {
alert('Еденица!');
} else {
alert('Не еденица!');
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question