3

I want to make multiple ajax calls synchronously from my javascript code. I want to load the SharePoint Online Lists data using ajax call(rest api). I want to load data from the first list and after successfully load the first list data I want to load another list data. How can I load the data synchronously?

I have tried this with the 'async:false'. But I have marked that it has been not supported in some browser.

Please suggest me!

Thanks

  • I am the first one to say you should not use async:false .. but there is no Browser restriction. jQuery deprecated it when using Promises, But without Promises async:false should still work in any browser – Danny '365CSI' Engelman Feb 14 '17 at 10:24
5

You can use the jQuery's when to get data as below:

function SPData() {
    function getJsonDataAsync(url) {
        // returning the $.ajax object is what makes the next part work...
        return $.ajax({
            url: url,
            method: "GET",
            contentType: "application/json",
            headers: {
                accept: "application/json;odata=verbose"
            }
        });
    }

    var requestURI1 = _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('List1')/items?&$orderby=Title"
    var requestURI2 = _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('List2')/items?&$orderby=Title"
    var requestURI3 = _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/getbytitle('List3')/items?&$orderby=Title"            
    var req1 = getJsonDataAsync(requestURI1);
    var req2 = getJsonDataAsync(requestURI2);
    var req3 = getJsonDataAsync(requestURI3);
    // now we can do the next line, because req1/2/3 are actually deferreds
    // being returned from $.ajax
    jQuery.when(req1, req2, req3).done(function(resp1, resp2, resp3) {
        /* do something with all of the requests here...
           resp1/2/3 correspond to the responses from each call and are each an
           array that looks like: [data, statusText, jqXHR], which means that your
           data is in resp1[0], resp2[0], etc. */
    });
}

Reference - REST API multiple calls

You can also use the batch api as below:

Just add reference to sp-rest-batch-execution.js and after that try below code:

var getEndPoint1 = appweburl + "/_api/web/lists/getbytitle('List1')/items?&$orderby=Title";

var getEndPoint2 = appweburl + "/_api/web/lists/getbytitle('List2')/items?&$orderby=Title";

var getEndPoint3 = appweburl + "/_api/web/lists/getbytitle('List3')/items?&$orderby=Title";

var commands = [];

batchRequest = new BatchRequest();
batchRequest.endpoint = getEndPoint1;
batchRequest.headers = { 'accept': 'application/json;odata=verbose' }
commands.push({ id: batchExecutor.loadRequest(batchRequest), title: "Rest Batch Get Items 1" });

batchRequest = new BatchRequest();
batchRequest.endpoint = getEndPoint2;
batchRequest.headers = { 'accept': 'application/json;odata=verbose' }
commands.push({ id: batchExecutor.loadRequest(batchRequest), title: "Rest Batch Get Items 2" });

batchRequest = new BatchRequest();
batchRequest.endpoint = getEndPoint3;
batchRequest.headers = { 'accept': 'application/json;odata=verbose' }
commands.push({ id: batchExecutor.loadRequest(batchRequest), title: "Rest Batch Get Items 3" });


batchExecutor.executeAsync().done(function (result) {
    var d = result;
    var msg = [];
    $.each(result, function (k, v) {
        var command = $.grep(commands, function (command) {
            return v.id === command.id;
        });
        if (command.length) {
            msg.push("Command--" + command[0].title + "--" + v.result.status);
        }
    });

    console.log(msg.join('\r\n'));

}).fail(function (err) {
    console.log(JSON.stringify(err));
});

Works well in SPO - SP-Rest-batch execution

If you are a fan of PnP JS like me, it also provides the batching as below:

var batchResults = [];
var batch = new $pnp.sp.createBatch();
$pnp.sp.web.lists.getByTitle("List1").items.inBatch(batch).get().then(function(d) {
  batchResults.push({ 
    custom01: d 
  });
});
$pnp.sp.web.lists.getByTitle("List2").items.inBatch(batch).get().then(function(d) {
  batchResults.push({ 
    custom02: d 
  });
});
$pnp.sp.web.lists.getByTitle("List3").items.inBatch(batch).get().then(function(d) {
  batchResults.push({ 
    custom03: d 
  });
});

batch.execute().then(function() {
  console.log(batchResults);
});

Update - for using PnP js core in IE , you need to add below references as well. jQuery is not required:

es6-promise

fetch

Usage:

<script type="text/javascript" src="/pathinyoursitecoll/es6-promise.min.js"></script>
<script type="text/javascript" src="/pathinyoursitecoll/fetch.js"></script>
<script type="text/javascript" src="/pathinyoursitecoll/pnp.js"></script>

Reference - PnP JS core

  • 1
    Does PnP need jQuery? I thought it had its own HttpClient .. – Danny '365CSI' Engelman Feb 14 '17 at 10:29
  • my bad, jQuery is not required for PnP js, usually i have used it along with jQuery, so had mentioned that. – Gautam Sheth Feb 14 '17 at 10:50
1

You can call one Ajax call on success of another Ajax Call.

// Assign Lists Name to one Array;
var listNameArray =["List1","List2", "List3"]
// Call function To get List Item
getMutipleList(0,listNameArray)

//This function we can call it recursively on success of Ajax Call
var getMutipleList = function (count, listNameArray) {
    try {
        var Url = webUrl + "/_api/web/GetByTitle('" + listNameArray[count] + "')/items";
        getRequest(Url, true).then(function (data) {
            count++;
            if (count < listNameArray.length) {
                getMutipleList(count, listNameArray);
            }
            else {

                //code
            }
        }).fail(onFail)
    }
    catch (ex) {
        alert("Please try agian. Something went wrong.")
        console.log(ex.message);
    }
}


var baseRequest = {
    url: "",
    type: ""
}

 //Ajax call to get list items
getRequest = function (endpoint, _async) {
    var dfd = $.Deferred();
    var request = baseRequest;
    request.type = "GET";
    request.url = endpoint;
    request.async = _async;
    request.headers = {
        ACCEPT: "application/json;odata=verbose"
    };
    dfd = $.ajax(request);
    return dfd.promise();
};

Click here to understand $.Deferred() and Deferred.Promise()

  • 1
    I am getting an error if I use this code. I am getting the error "baseRequest is not defined" – Krunal Patel Feb 14 '17 at 12:00
  • Now Try, "baseRequest" is variable that I have initialize – Bharat Khunti Feb 15 '17 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.