Rens Tillmann Rens Tillmann - 1 month ago 8
Javascript Question

Ajax success: {return false;}

I want to return

false
from
$.ajax
when
success
is complete:

$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
return false;
}
});


This doesn't work. Is there a work around?

Answer

From your post I guess that you call a function that contains the $.ajax() and try to return false to that function. but you can't do that such way, because AJAX is asynchronous.

It's better to call a function from the ajax success function like following:

$.ajax({
    url: '' + $website_url + 'queries/voorraad_berekenen.php',
    type: 'post',
    data: {
        aantal: $(this).parent('form').children('.quantity').val(),
        item_number_1: $(this).parent('form').children('.item_number_1').val()
    },
    success: function(result) {
        var returned = true;
        if(some_condition_not_satisfied) {
          returned = false;
        } else {

        }
        // call a function
        calledFromAjaxSuccess(returned);
    }
});

function calledFromAjaxSuccess(result) {
  if(result) {
    alert('TRUE');
  } else {
    alert('FALSE');
  }
}
Comments