Search code examples
javascriptasp.netajaxrazor-pages

How to get result from AJAX call before function returns?


My page has a button that calls a Razor Page page handler to delete the associated item.

<a class="delete-item" data-id="@item.Id" asp-page-handler="delete" asp-route-id="@item.Id"><img src="/images/delete.png" title="Delete" /></a>

I've defined a Javascript click handler. I need that handler to return false if the item should not be deleted.

$('.delete-item').on('click', function (e) {
    var id = $(this).data('id');
    var tr = $(this).closest('tr');
    var td = tr.find('.item-description');

    // Get number of lease details for this lease
    $.ajax({
        type: 'GET',
        url: '?handler=LeaseDetailCount',
        contentType: 'application/json',
        dataType: 'json',
        data: { 'leaseId': id },
    })
    .done(function (response) {
        var description = 'Delete "' + description + '"? Are you sure? This cannot be undone.\r\n\r\n';
        if (response.count == 0)
            description += 'This lease has no lease details.'
        else
            description += 'WARNING: This lease has ' + response.count + ' lease detail(s).';
        if (!confirm(description))
            return false;
    })
    .fail(function (response) {
        alert(response.responseText);
    })
    //.always(function (response) {
    //});
}

The problem, of course, is that the AJAX call is asynchronous. And so it returns before my confirmation is displayed.

How can I get the code above to work as I want?


Solution

  • If you not wish to set asp-page-handler for the anchor tag, it is possible. As you mentioned

    AJAX call is asynchronous

    we can't predict which result come first, href navigation or onclick AJAX response

    <a class="delete-item" data-id="@item.Id"><img src="/images/delete.png" title="Delete" /></a>
    

    In AJAX .done event, If the confirmation is OK page redirect to delete handler window.location.href = "/?id=" + id + "&handler=delete";

    .done(function (response) {
        ......
        .......
        if (!confirm(description))
            return false;
        else
            window.location.href = "/?id=" + id + "&handler=delete";
    })