Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading gif image while jQuery ajax is running

I am trying to show a loading image while my ajax call is running, however using the beforeSend attribute is not changing my result area.

$.ajax({
  url: "/answer_checker.php",
  global: false, type: "POST", 
  data: ({...clipped...}), 
  cache: false,
  beforeSend: function() {
    $('#response').text('Loading...');
  },
  success: function(html) {
    $('#response').html(html);
  }
}

Thanks in advance.

like image 723
Alan Whitelaw Avatar asked Dec 15 '10 10:12

Alan Whitelaw


People also ask

How display loading image or loader when AJAX call is in progress?

You can display the image just before this call to $. ajax() and then hide/remove the image in the post handler function (just before your . empty()/. append(data) calls.

How do you show a loader until AJAX response?

Answer: Use the ajaxStart() and ajaxStop() MethodWhile working with Ajax, showing a loading spinner or displaying a message with some animation like "Loading... Please Wait" is popular way to indicate the user that Ajax request is in progress.

Can I use AJAX with jQuery?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!


2 Answers

I had a similar problem. To resolve my issue, I replaced the .text, in the beforeSend section, with .html and created a html tag to insert into the element that holds my status. The success function did not replaced the content created by the .text() function but it did replace content created by the .html() function.

$.ajax({
  url: "/answer_checker.php",
  global: false, type: "POST", 
  data: ({...clipped...}), 
  cache: false,
  beforeSend: function() {
    $('#response').html("<img src='/images/loading.gif' />");
  },
  success: function(html) {
    $('#response').html(html);
  }
}
like image 139
ackqpunk Avatar answered Sep 30 '22 01:09

ackqpunk


I have a solution, it may not be the best way to do it but it has worked in this case.

$('input').keyup(function () {

  $('#response').text('loading...');

  $.ajax({
    url: "/answer_checker.php",
    global: false, type: "POST", 
    data: ({...clipped...}), 
    cache: false,
    success: function(html) {
      $('#response').html(html);
    }
  });
});

By setting the resonce content before calling the ajax function it remains showing the loading text until the ajax call updates the same content.

Thanks to everyone who took the time to answer.

Alan

like image 28
Alan Whitelaw Avatar answered Sep 30 '22 02:09

Alan Whitelaw