-1

I am trying to call synchronous call for getting data count using ajax call.

Here is my Jquery Code:

var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();

function tilesCount(tilename, count)
{
    var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
    count = 0;

    $.ajax({
        url: url,
        dataType: 'json',
        success: function(data) {
            $(data.value).each(function (i, folder) {
                count = count + 1;
            });
            console.log("Call 1: " + count)
            ItemCount.resolve(count);
            return count;
        },
        error: function(error){
            console.log("Error: " + JSON.stringify(error));
            ItemCount.reject;
        }
    });
}

$(document).ready(function () {
    var count = tilesCount("");
    $.when(count).then(function(data){
        console.log("Call 2: " + data); 
    });
});

Output:
Call 1: 1
Call 2: undefined

Synchronous call working perfectly, but I am getting data as undefined

Ubiquitous Developers
  • 3,637
  • 6
  • 33
  • 78

1 Answers1

1

Since ajax is asynchronous return count; will be empty

var count = tilesCount("");

So the best solution is to just passed a callback function inside your method which can be call whenever your ajax is completed

function tilesCount(tilename, count, callback)

Wrap this inside your callback function

function(count) { 
    $.when(count).then(function(data){
        console.log("Call 2: " + data); 
    });
}

so your $(document).ready will be like this and just add parameter count inside the callback

$(document).ready(function () {
    tilesCount("", "", function(count) { 
        $.when(count).then(function(data){
            console.log("Call 2: " + data); 
        });
    });
});

your javascript code would be like this now

var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();

function tilesCount(tilename, count, callback)
{
    var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
    count = 0;

    $.ajax({
        url: url,
        dataType: 'json',
        success: function(data) {
            $(data.value).each(function (i, folder) {
                count = count + 1;
            });
            console.log("Call 1: " + count)
            ItemCount.resolve(count);
            return callback(count);
        },
        error: function(error){
            console.log("Error: " + JSON.stringify(error));
            ItemCount.reject;
        }
    });
}

$(document).ready(function () {
    tilesCount("", "", function(count) { 
        $.when(count).then(function(data){
            console.log("Call 2: " + data); 
        });
    });
});
Beginner
  • 4,118
  • 3
  • 17
  • 26