1

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 ?

GGO
  • 2,678
  • 4
  • 20
  • 42
  • if you define your .NET endpoints as async tasks, you perhaps won't have this problem. Also maybe don't trigger the submit until the user has typed at least 3 characters. Also lastly consider using an autocomplete plugin rather than a form submit, which might work a bit more nicely. – ADyson Oct 10 '17 at 14:47
  • Thanks for recommandation, but it's async tasks yet, and i can't change the field into autocomplete. it's an exisiting interface. – GGO Oct 11 '17 at 07:15

1 Answers1

0

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

});
Rohit Kumar
  • 1,777
  • 2
  • 13
  • 26
  • 1
    I would prefer without removing the unobtrusive ajax call, but if i don't have any others possibilities i will use this. – GGO Oct 11 '17 at 07:19