1

I've got a problem since I've migrated from jQuery 1.11 to jQuery 3.0. I'm running a jQuery POST request and before the migration it first finished the html(data.responseText) and then moved on with the code that follows. Like this:

$.ajax({
    type: "POST",
    url: "/files/" + url,
    data: $("#entryForm").serialize() + '&journal_id=' + journalId,
    complete: function(data) {
        $('#saveResults').html(data.responseText);
        alert("function done");
    }
});

In the data.responseText there is an alert which runs first and after complete the function html() the other alert("function done") was running.

After the migration the alert("function done") is running first so it appears the function html() is not finished at this point because the alert from the responseText is coming after the alert("function done"). So I tried this:

$.ajax({
    type: "POST",
    url: "/files/" + url,
    data: $("#entryForm").serialize() + '&journal_id=' + journalId,
    complete: function(data) {
        $('#saveResults').html(data.responseText).promise().done(function() {
            alert("function done");
        });
    }
});

Unfortunately this didn't fix my problem. Anyone an idea how to fix it?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Leon van der Veen
  • 1,652
  • 11
  • 42
  • 60
  • 3
    The problem sounds very odd as `html()` is synchronous (which is why your second attempt doesn't work) so should complete before the `alert()` is shown. I can only assume it's an inconsistency with the browser renderer where the Ui doesn't get updated immediately with the DOM and the `alert()` blocks the thread. You could try putting the `alert()` in a `setTimeout()` call with a short timeout, say 10ms. – Rory McCrossan Nov 24 '16 at 09:11
  • Possible duplicate of [jquery event after html() function](http://stackoverflow.com/questions/11826484/jquery-event-after-html-function) – inubs Nov 24 '16 at 09:13
  • @RoryMcCrossan Remember that jQuery handles ` – Barmar Nov 24 '16 at 09:14
  • @Barmar I guess you are right and it could be to avoid sync warning regarding any script handled by `html()` method, as on older jq version. – A. Wolff Nov 24 '16 at 09:24
  • You might want to ask this question in the jQuery Forum. You're more likely to find someone with intimate knowledge of the internals, and how they changed between releases. – Barmar Nov 24 '16 at 09:25

1 Answers1

0

Try this.

.html is set when response is back and when success is completed, complete is ran

success: function(data){
    $('#saveResults').html(data.responseText);
},
complete: function(data)
{
    alert("function done");
}
Luminous_Dev
  • 614
  • 6
  • 14