rjmcb
rjmcb

Reputation: 3745

ajaxStart and ajaxStop for a specific event

How can I bind an ajaxStart function for a specific event, using :

$(document).ajaxStart(function () {
  alert("started");
});
$(document).ajaxStop(function () {
  alert("Ended");
});

Tried this code but it runs whenever autocomplete starts.

Scenario must be like this : whenever I submit a form, that function will be called. But when I'm just fetching values using autocomplete via ajax, ajaxStart and ajaxStop shouldn't be called.

Upvotes: 2

Views: 2716

Answers (3)

Max Allan
Max Allan

Reputation: 640

It is better if you uses the main function and it's sub-functions.

$.ajax({
 url: 'url_to_page'
 beforeSend: function(req){ //Before the request is taking off},
 error: function(req){ //If there were a error},
 success: function(req){ //When it all was done}
});

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382806

But when I'm just fetching values using autocomplete via ajax, ajaxStart and ajaxStop shouldn't be called.

You can create a boolean variable to keep track of whether user is typing or not something like:

<script>
var isTyping = false;

// inside your autocomplete handler set isTyping to true

$(document).ajaxStart(function(){
    if (! isTyping) alert("started");
});
$(document).ajaxStop(function(){
    if (! isTyping) alert("Ended");
});

</script>

Upvotes: 3

coolguy
coolguy

Reputation: 7954

 $.ajax({
      url :'your url',
      data: {
           //data to send if any
      },
      type: 'POST',
      success:function(msg){
           //eqv to ajaxstop if OK
      },
      beforeSend:function(){
           //before ajax starts
      },
      error:function(){
           //failure in ajax
      }
 });

Upvotes: 1

Related Questions