0

I want to wait until a current foreach has fully completed before doing the next function, here is the code im using

$(function(){
    $.ajax({
      url: "/myurl",
      dataType: "text",     
      success: function( data, textStatus, jqXHR ) {
        var parsedtext = data.split(',');
        $.each(parsedtext, function()  {
            $("#text").append(this);
        });
      }
    });
});

I have tried adding .done() to parts of my code but noting has worked, I tried this

$(function(){
    $.ajax({
        url: "/myurl",
        dataType: "text",     
        success: function( data, textStatus, jqXHR ) {
            var parsedtext = data.split(',');
            $.each(parsedtext, function()  {
                $("#text").append(this);
            })
            .done(function() {
                alert('done');
                startnewfuction();
            });
        }
    });
});
dns_nx
  • 3,651
  • 4
  • 37
  • 66
brandbei37
  • 501
  • 3
  • 13
  • possible duplicate of https://stackoverflow.com/questions/2358205/invoking-a-jquery-function-after-each-has-completed – gogaz Aug 16 '18 at 11:59
  • 3
    [jQuery.each](http://api.jquery.com/jquery.each/) is synchronous which means that it is done when it returns. – Titus Aug 16 '18 at 12:01
  • Have you tried `$.when(function1()).then(function2());`? – Suprabhat Biswal Aug 16 '18 at 12:01
  • @SuprabhatBiswal no i havent yet, please could you give me an example? – brandbei37 Aug 16 '18 at 12:02
  • Just replace function1() with $.each() part and function2() with startnewfuction(). simple. – Suprabhat Biswal Aug 16 '18 at 12:03
  • Just like @Titus mentioned in his comment `$.each` is synchronous so calling startnewfuction() after `$.each` will also work. – Suprabhat Biswal Aug 16 '18 at 12:05
  • Are you certain that your ajax is able to complete without error? You might want to add the `error` block to see if there is any error. Something like `error: function ( xhr, msg ) { alert(xhr.status + ' - ' + msg); }` – Chan MT Aug 16 '18 at 12:07

0 Answers0