0

I am iterating List A and fetching each items title. Then I match the title against a column in List B. If a match is found I add relevant columns in list B and output. I have put 2 items in list A as test data. Though I can see the code in List B being called twice (I get the alert 'Part2 -' xx) I only get the 'Output alert' once and only the last item in List A is being worked on. I think the problem is in the 2nd section while loop. Any ideas please?

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(TeamRequests, "SP.js");

function TeamRequests() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('TeamRequests');        
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);        
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededTeamRequests), Function.createDelegate(this, this.onQueryFailedTeamRequests)); 
}

function onQuerySucceededTeamRequests(sender, args) {
    var listItemInfo = ''; var iCount=0;

    var listItemEnumerator = collListItem.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();

       listItemInfo += '\nID: ' + oListItem.get_id() +  '\nTitle: ' + oListItem.get_item('Title');

// Code to get Mandays
//alert (oListItem.get_item('Title'));
    Mandays(oListItem.get_item('Title'));

        }
  // alert (listItemInfo);
}

function onQueryFailedTeamRequests(sender, args) {
    alert('TeamRequests Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}    
function Mandays(trTitle)
{
    alert (trTitle);
    this.trTitle = trTitle;
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Mandays');        
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);        
    //clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededMandays), Function.createDelegate(this, this.onQueryFailedMandays));        

     clientContext.executeQueryAsync(Function.createDelegate(this, function(){onQuerySucceededMandays(trTitle);}), Function.createDelegate(this, this.onQueryFailedMandays));        



}

//function onQuerySucceededMandays(sender, args) {


function onQuerySucceededMandays(trPassTitle) {

alert ('part2 -' +  trPassTitle);
    var option1=0; option2=0; option3=0;

    var listItemInfo = ''; var iCount=0;

    var listItemEnumerator = collListItem.getEnumerator();


    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();

       listItemInfo += '\nID: ' + oListItem.get_id() +  '\nTitle: ' + oListItem.get_item('Title')+  '\nTRTitle: ' + oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue();

        //test for Team
        alert ('trPassTitle -'+ trPassTitle + '\n Man -'+ oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue());
        if (trPassTitle == (oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue())) 
        {
            if (oListItem.get_item('Item') == 'Option1') {
                option1 += parseFloat(oListItem.get_item('EstCost')); }
            if (oListItem.get_item('Item') == 'Option2') {
                option2 += parseFloat(oListItem.get_item('EstCost')); }
            if (oListItem.get_item('Item') == 'Option3') {
                option3 += parseFloat(oListItem.get_item('EstCost')); }
        }

    } // end while
    alert ('Output Option1 ' + option1 + '\nOption2 ' + option2 + '\nOption3 ' + option3);

    //  alert (listItemInfo);
    //return;
}

function onQueryFailedMandays(sender, args) {

    alert('Mandays Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}



</script>
7
  • seems like you have an exception intercepting your code - did you check the dev tools? press F12 in your browser to access them.
    – Mx.
    Commented Jun 19, 2015 at 8:25
  • Developer tools report: SCRIPT5022: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. sp.runtime.js?rev=IGffcZfunndj0247nOxKVg%3D%3D, line 2 character 23256 Commented Jun 19, 2015 at 8:43
  • with the devtools you can check wich line the error occurs and even debug your code - your problem is a pretty obvios one. when you try to access an item that you havent load via ctx.load, this error occurs. I bet its in line var listItemEnumerator = collListItem.getEnumerator();
    – Mx.
    Commented Jun 19, 2015 at 8:46
  • When I 'step over' code var listItemEnumerator = collListItem.getEnumerator(); is highlighted. I tried adding clientContext.load(collListItem,'Include(Item,TeamRequest_x003a_Title,Title,Id)'); but error remains Commented Jun 19, 2015 at 9:07
  • probably the wrong scope. but you should have enough infomations to solve it yourself. fiddling arround with the devtools will help you learn the language
    – Mx.
    Commented Jun 19, 2015 at 9:20

2 Answers 2

0

I refactored (not tested!) your code - you shouldnt have any scoping issues now.

/* global SP */
/* global ExecuteOrDelayUntilScriptLoaded */
(function() {
    //here we are in our own scope - no messing with other globals (SharePoint has a lot)
    ExecuteOrDelayUntilScriptLoaded(function() {
        //if you use a function only once - you dont necessarily need a function 
        var clientContext = new SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('TeamRequests');
        var camlQuery = new SP.CamlQuery.createAllItemsQuery();
        var collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
            function() {
                //success
                var listItemInfo = '';
                var listItemEnumerator = collListItem.getEnumerator();

                while (listItemEnumerator.moveNext()) {
                    var oListItem = listItemEnumerator.get_current();
                    listItemInfo += '\nID: ' + oListItem.get_id() + '\nTitle: ' + oListItem.get_item('Title');
                    // Code to get Mandays
                    Mandays(oListItem.get_item('Title'));
                }
                //alert (listItemInfo);
            },
            function(sender, args) {
                console.log(sender);
                console.log(args);
                alert('TeamRequests Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    }, "SP.js");

    function Mandays(trTitle) {
        var clientContext = new SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('Mandays');
        var camlQuery = new SP.CamlQuery.createAllItemsQuery();
        var collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
            function() {
                //success
                alert('part2 -' + trTitle);
                var option1 = 0,
                    option2 = 0,
                    option3 = 0,
                    listItemInfo = '';

                var listItemEnumerator = collListItem.getEnumerator();
                while (listItemEnumerator.moveNext()) {
                    var oListItem = listItemEnumerator.get_current();

                    listItemInfo += '\nID: ' + oListItem.get_id() + '\nTitle: ' + oListItem.get_item('Title') + '\nTRTitle: ' + oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue();

                    //test for Team
                    alert('trPassTitle -' + trTitle + '\n Man -' + oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue());
                    if (trTitle == (oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue())) {
                        if (oListItem.get_item('Item') == 'Option1') {
                            option1 += parseFloat(oListItem.get_item('EstCost'));
                        }
                        if (oListItem.get_item('Item') == 'Option2') {
                            option2 += parseFloat(oListItem.get_item('EstCost'));
                        }
                        if (oListItem.get_item('Item') == 'Option3') {
                            option3 += parseFloat(oListItem.get_item('EstCost'));
                        }
                    }
                }
                alert('Output Option1 ' + option1 + '\nOption2 ' + option2 + '\nOption3 ' + option3);
            },
            function(sender, args) {
                console.log(sender);
                console.log(args);
                alert('TeamRequests Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    }
}());
0

you should not call a function in loop which is having executeQueryAsyc() method in it because of the asynchronous nature of the method. The while loop will create multiple async calls and code execution will get messed up to decide which querySucceed() method to execute. Thats why the error The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
I have made some changes to your code. Check if it works for you.

    ExecuteOrDelayUntilScriptLoaded(TeamRequests, "SP.js");
    function TeamRequests() {
        var clientContext = new SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('TeamRequests');        
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View></View>');
        this.collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);        
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededTeamRequests), Function.createDelegate(this, this.onQueryFailedTeamRequests));        
    }
    function onQuerySucceededTeamRequests(sender, args) {
        var listItemInfo = ''; var iCount=0;
        var listItemEnumerator = collListItem.getEnumerator();
        var arrTitle = [];
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            listItemInfo += '\nID: ' + oListItem.get_id() +  '\nTitle: ' + oListItem.get_item('Title');
            //Mandays(oListItem.get_item('Title'));
            if(oListItem.get_item('Title')!= null){
                arrTitle.push(oListItem.get_item('Title'));
            }
        }
        Mandays(arrTitle);
    }
    function onQueryFailedTeamRequests(sender, args) {
        alert('TeamRequests Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    function Mandays(arrTitle)
    {
        var clientContext = new SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('Mandays');        
        var camlQuery = new SP.CamlQuery();
        var strQueryStart = "<View><Query><Where><In><FieldRef Name='TeamRequest_x003a_Title' /><Values>";
        var strQueryMiddle = "";
        for(var i = 0; i < arrTitle.length; i++){
            strQueryMiddle += "<Value Type='Lookup'>"+arrTitle[i]+"</Value>";  /////for getting only those "TeamRequest_x003a_Title" which are equals to Title from "TeamRequests"
        }
        var strQueryEnd = "</Values></In></Where></Query></View>";
        camlQuery.set_viewXml(strQueryStart + strQueryMiddle + strQueryEnd);
        this.collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);        
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededMandays), Function.createDelegate(this, this.onQueryFailedMandays));
    }
    //function onQuerySucceededMandays(sender, args) {
    function onQuerySucceededMandays(trPassTitle) {
        var option1=0; option2=0; option3=0;
        var listItemInfo = ''; var iCount=0;
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            listItemInfo += '\nID: ' + oListItem.get_id() +  '\nTitle: ' + oListItem.get_item('Title')+  '\nTRTitle: ' + oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue();
            /////we don't need this condition here as we already have such records which full fill this condition
            //if (trPassTitle == (oListItem.get_item('TeamRequest_x003a_Title').get_lookupValue())) 
            //{
            if (oListItem.get_item('Item') == 'Option1') {
                option1 += parseFloat(oListItem.get_item('EstCost')); }
            if (oListItem.get_item('Item') == 'Option2') {
                option2 += parseFloat(oListItem.get_item('EstCost')); }
            if (oListItem.get_item('Item') == 'Option3') {
                option3 += parseFloat(oListItem.get_item('EstCost')); }
            //}
        } // end while
        alert ('Output Option1 ' + option1 + '\nOption2 ' + option2 + '\nOption3 ' + option3);
    }
    function onQueryFailedMandays(sender, args) {
        alert('Mandays Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
3
  • Hi The code executes but result is incorrect. When I add a few items with the same TeamRequest then I get a single alert showing totals of Option1-3, this is ok. If I add another few different TeamRequest I still only get the same single alert but now summing up all the options. I need to display a matrix with TeamRequest, Option1,Option2, Option3 for every Team Request in the TeamRequest list (in the TeamRequest list I have a single instance of every team and in the Mandays I have multiples, the options of the multiples are needed to be added only) Commented Jun 22, 2015 at 11:55
  • Try using alert ('Output Option1 ' + option1 + '\nOption2 ' + option2 + '\nOption3 ' + option3); in while loop so that in each iteration it will show the values of options 1, 2 & 3.
    – Yayati
    Commented Jun 22, 2015 at 13:14
  • It outputs the values of every item in Mandays without any order. in the while I need to add condition that checks for the value in the array from the calling function trPassTitle . How can it be passed ? Commented Jun 22, 2015 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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