A
A
Alexey2021-04-12 17:53:48
AJAX
Alexey, 2021-04-12 17:53:48

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{
        //...
    }
});


The already_vote() function contains an ajax request:

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


Actually, you need to get the isVoted variable in the click event. A simple return doesn't work because ajax asynchronous request. I know that you can just use async: false, then it works as it should. But this feature is considered obsolete (which is reported by the console in the browser) and may stop working in the future. I googled that it is correct to do this through callback functions, but something does not work out. Tell me how you need.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StiflerProger, 2021-04-12
@RussianNinja

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 {
        //...
    }
});
    
});

Promise option:
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 {
        //...
  }
    
});

N
Nadim Zakirov, 2021-04-12
@zkrvndm

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 question

Ask a Question

731 491 924 answers to any question