knowledgeseeker
knowledgeseeker

Reputation: 1203

ASP.Net Mvc Ajax Request in Progress

I am currently using @Ajax.ActionLink to call some controller action in ajax fashion .Is there any way to detect if there is already a ajax request running/pending on page?The functionality i want is pretty basic i.e. once user clicks the link he should wait for either request to succeed or fail.He should be allowed to click it again( generate a new request to server).

I could have disabled the link but would not like to do that(i guess a href cant be disabled)

Upvotes: 0

Views: 755

Answers (2)

Vaibhav J
Vaibhav J

Reputation: 1334

Try this,

This Code will check for any executing ajax request before making a new ajax request. You can subscribe OnSuccess, OnFailure callbacks also :

@Ajax.ActionLink("Home", "Index", "Home", new AjaxOptions { 
    OnBegin = "return onBegin();",
    OnComplete = "onComplete",
    UpdateTargetId = "article_site"
})

and then:

var request_executing = false;
function onBegin() {
    if (request_executing == true) {return false ;}
    request_executing = true;
    return true;
}

function onComplete() {
    request_executing = false;
}

Or a jquery alternative (so you don't need that bloated jquery.unobtrusive-ajax.js file)

@Html.ActionLink("Click Me", "ajaxactions", null, new { id = "btn", @class = "btn btn-default" })

var isExecuting = false;
$('#btn').click(function(e) {
  if(isExecuting) {
    e.preventDefault();
    return;
  }
  isExecuting = true;
  $(this).addClass('someClass'); // optional - to give some visual effect to the link while loading
  $.get('@Url.Action("ajaxactions")', function(data) {
    $('#content').append(data);
    $(this).removeClass('someClass');
    isExecuting = false;
  });
});

Upvotes: 2

Alexey  Shumeyko
Alexey Shumeyko

Reputation: 117

Try jQuery ajax. It can do async and sync requests to server. It's quite simple to use. http://api.jquery.com/jquery.ajax/ async=true by default.

Upvotes: 0

Related Questions