Search code examples
c#jqueryasp.net-mvcajax.beginformunobtrusive-ajax

Stop previous unobtrusive ajax call


I have a form like :

@using (Ajax.BeginForm("List", null, new AjaxOptions() { UpdateTargetId = "results" }, new { id = "myform" }))
{
     <input id="search" type="text" value="" />
}

I declare javascript to send submit when user presses a key in my Search box :

<script type="text/javascript">
    $("#search").on("keyup", function ()
    {
        $("#myform").submit();
    });
</script>

But when users search quickly, browser start multiple ajax request, and wait the end of each call one by one. How to stop the previous ajax call before sending another without removing ajax unobtrusive ?


Solution

  • I would suggest instead of directly calling $("#myform").submit(); Break it down to an $.ajax() request & abort if before making another one

    $("#search").on("keyup", function (){
        var xhr;
    
      if (xhr){ 
               xhr.abort();  //stop previous ajax          
        }
    
         xhr = $.ajax({
                   type: "GET",
                    url: "@Url.Action(list)",
                  data : {formdata : $("#myform").serialize() },
                success: function(response){
                      // do some stuffs with $("#results")
                 }
          });                  
    
    });