Borsn Borsn - 3 months ago 13
Ajax Question

Loading wont show up on ajax post request

I am using the jQuery below in an autocomplete input field.

Now, I'd like for a spinner to show up while the ajax is waiting for the response from the server.

I am using

search:
to show the loading div. And then
open:
to hide it. And finally success to display the result.

$(document).ready(function(){
$('#search_field').keyup(function(){
var search = $(this).val();
if(search != '')
{
$.ajax({

url: 'search.php',
method: 'POST',
data: {search:search},

search: function()
{
$('#search_loader').fadeIn('fast', 'swing');
},

open: function()
{
$('#search_loader').fadeOut('fast', 'swing');
},

success: function(data)
{
if(data == '') {
$('#autocomplete_result').fadeOut('fast', 'swing');
} else {
$('#autocomplete_result').fadeIn('fast', 'swing');
$('#autocomplete_result').html(data);
}
}


});
}
});


});


However neither
search:
or
open:
work.

New with JS, so can anyone tell me what I'm doing wrong?

Answer

Check this http://api.jquery.com/jquery.ajax/ . There is no open and search options .Try to use beforeSend and complete ,also set fadeIn fadeOut to "slow"

$(document).ready(function(){  
      $('#search_field').keyup(function(){  
           var search = $(this).val();  
           if(search != '')  
           {  
                $.ajax({    
                     url: 'search.php',  
                     method: 'POST',  
                     data: {search:search},    
                     beforeSend : function()
                     {
                         $('#search_loader').fadeIn('slow', 'swing');
                     },   
                     complete : function()
                     {
                         $('#search_loader').fadeOut('slow', 'swing');
                     },

                     success: function(data)  
                     {     
                         if(data == '') {
                             $('#autocomplete_result').fadeOut('fast', 'swing');
                         } else {
                             $('#autocomplete_result').fadeIn('fast', 'swing'); 
                             $('#autocomplete_result').html(data); 
                         }
                     }
                });  
           }  
      });  
 });