1

I have now tried to read and understand about promises, asynchronous ajax calls and .when and .then. However I am still experiencing some problems with old content being updated and inserted.

So please let me know if I am doing something wrong or if there is a better approach.

My code:

// Loading template
function getTemplate(template) {
    return $.ajax({
        dataType: "json",
        url: "/externalBookingModule/jsonp_example.php?" + template + "&url=" + document.domain + "&callback=?",
        success: function(result){
            $("#template").html(result['template']);
            console.log(result['template']);
        }
    });
}

// Loading JSON content
function loadContent(content, div) {
    return $.ajax({
        dataType: "json",
        url: "/externalBookingModule/jsonp_example.php?" + content + "&url=" + document.domain + "&callback=?",
        success: function(result){
            var template = $('#template').html();
            Mustache.parse(template);   // optional, speeds up future uses
            var rendered = Mustache.render(template, result);
            $(div).html(rendered);
        }
    });
}

// buttons
$("#target").on("click", '.nextButton', function() { 
    $.when(
        getTemplate("templateCustomerInfo", "#template"))
    .then(
        loadContent("test1", "#target")
    );
});     
$("#target").on("click", "#searchDatesButton", function() {
    $.when(
        getTemplate("templateDates", "#template"))
    .then(
        loadContent("test1", "#searchContent")
    );
});

Thank you very much!

Kasper Sommer
  • 409
  • 1
  • 6
  • 18
  • `However I am still experiencing some problems with old content being updated and inserted` What does this mean? What is the outcome and what are you actually expecting? – StudioTime Jun 21 '17 at 06:39
  • Sorry for not making that clear. E.g. the nextButton click should update first the #template and then the #target. What happens is that the #target is updated with old #template content - and only afterwards the #template is updated. To me it seems that the .then is not waiting for the .when, so I do not know if I'm handling the promises incorrectly? – Kasper Sommer Jun 21 '17 at 06:42
  • You're not passing the result of the `.when()` into the `.then()` - have a look at this: https://api.jquery.com/jquery.when/ - all the examples show that you get the result of the call and pass it along – StudioTime Jun 21 '17 at 06:49
  • Yes. So I should move the success part to the .then and handle it there instead? Like: `$("#target").on("click", '.nextButton', function() { $.when( getTemplate("templateCustomerInfo", "#template")) .then( function(result) { $("#template").html(result['template']); console.log(result['template']); } loadContent("test1", "#target") ); });` – Kasper Sommer Jun 21 '17 at 06:56
  • 1
    It seems to work! Thank you :) – Kasper Sommer Jun 21 '17 at 20:01

0 Answers0