I have a function to add a record to database that uses Ajax with C# web service. Prior to updating DB I call another function to validate input that also uses Ajax. So, I need the validate function to finish before continuing with the one adding the record.
I know due to asynchronous nature of ajax I have to use promise/deferred but just can't get my head wrapped around it to set it up properly.
Updated
function validate() {
    var deferred = $.Deferred();
    $.ajax({
        url: "path/to/web/service",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: params,
    }).done(function (result) {debugger
        if (!result || result.d === "") {
            isValid = false;
        }
        else {
            var duplicate = JSON.parse(result.d);
            switch (duplicate) {
                case DuplicateData.Name:
                    isValid = false;
                    break;
                case DuplicateData.ID:
                    isValid = false;
                    break;
            }
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
    });
    deferred.resolve(isValid);
    return deferred.promise();
    //return isValid;
}
$(document).on("click", "#btnAdd", function (event) {debugger
    $.when(validate())
        .then(function(isValid) {
            if (isValid) {
                $.ajax({
                    url: "path/to/another/webservice",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: some_param,
                }).done(function (result) {
                    addNewRecord();                       
                )}.fail(function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
                });
            }
    })
});
function addNewRecord(){
    // add record to DB
}
 
    