LA_
LA_

Reputation: 20409

How to do ajax request and html element update in background?

I have html form with three elements - buttons start and stop and text area. Once start button is pressed, I would like to do multiple ajax requests and once result is received to update the text area, once stop is pressed, processing of ajax requests should be stopped.

I tried to do something like below:

$(document).ready(function(){
  var inProgress = false;

  $("#stop").click(function() {
    inProgress = false;
  });

  $("#start").click(function() {
    inProgress = true;
    while (inProgress) {
      $('#textarea').html($('#textarea').val()+sometext+'\n');
      $.ajax({url: 'http://example.com'})
      .done(function(data, textStatus, jqXHR) {
         $('#textarea').html($('#textarea').val()+someresult+'\n');
      });
    }
  });

But it doesn't work as expected - browser tab hangs. What is wrong with my code?

Upvotes: 0

Views: 960

Answers (3)

Bonomi
Bonomi

Reputation: 2743

Probably because the browser is busy doing requests and it cannot listen other events. Try to put the code in a function and then use the

setTimeout( function_reference, timeoutMillis );

with a reasonable timeout.

See this code as an example:

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    // add a zero in front of numbers<10
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById("txt").innerHTML = h+ ":" + m + ":" + s;
    t = setTimeout(function(){startTime()}, 500);
}

function checkTime(i) {
    if (i<10) {
        i = "0" + i;
    }
    return i;
}

Upvotes: 0

laruiss
laruiss

Reputation: 3816

Well, since $.ajax is asynchronous by default, you are making a loooot of XHR (ajax calls) ! ;-)

Try this :

$(document).ready(function(){
  var inProgress = false;

  $("#stop").click(function() {
    inProgress = false;
  });

  $("#start").click(function() {
    inProgress = true;
    refresh();
  });

  function refresh() {    
      $('#textarea').html($('#textarea').val()+sometext+'\n');
      $.ajax({url: 'http://example.com'})
          .done(function(data, textStatus, jqXHR) {
             $('#textarea').html($('#textarea').val()+someresult+'\n');
             if (inProgress) refresh();
          });
  }
});

Upvotes: 1

kien
kien

Reputation: 195

Don't use while loop. You should do it in an asynchoronous way: At the end of .done function, put another asynchronous ajax call.

// other stuff goes here

function doRequest() {
      $.ajax({url: 'http://example.com'})
      .done(function(data, textStatus, jqXHR) {
         $('#textarea').html($('#textarea').val()+someresult+'\n');

         if (inProgress) doRequest();
      });
}

$("#start").click(function() {
    inProgress = true;
    $('#textarea').html($('#textarea').val()+sometext+'\n');
    doRequest();
});

Upvotes: 1

Related Questions