Solved

JavaScript Scope issue

Posted on 2016-11-25
4
20 Views
Last Modified: 2016-11-25
Hi All,

Please see an excerpt of my code below.  I am using SharePoint 2010 and JSOM to retrieve data from my list.

My getID() is returning 'undefined'.  I'm assuming it's a scope issue but not sure how to fix it. Any ideas would be great.

// JavaScript source code
$(document).ready(function () {
    SP.SOD.executeOrDelayUntilScriptLoaded(retrieveData, "sp.js");

    $("#procPlan").on("click", function () {
        ppConstruction_addListItem();

        //Empty fields after submit
        $("#origDate").val('');
        $("#ppcSetAside").val('');
    });
});

var getQueryString = function (field, url) {
    var href = url ? url : window.location.href;
    var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
    var string = reg.exec(href);
    return string ? string[1] : null;
};

itemProjectNumber = getQueryString('projNumber');

function retrieveData() {
    getListData("Project Module", "queryError");
    getListData("Project Projections", "Procurement Plan (Design)");
    getListData("Project Projections", "Design Award");
    getListData("Project Projections", "Procurement Plan (Construction)");
    getListData("Project Projections", "Construction Award");

    var itemID = getID(itemProjectNumber, 'Procurement Plan (Design)');
    alert("itemID: " + itemID);  //<-- Returns '[b]itemID:undefined[/b]'
}


function getID(pid, category) {
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Project Projections');

    if (itemProjectNumber) {
        var prjQry = "<View><Query><ViewFields>" +
      					"<FieldRef Name='ID' />" +
      					"<FieldRef Name='PlanningCategory' />" +
      					"<FieldRef Name='ProjectNumber' />" +
   					 "</ViewFields>" +
				     "<Where>" +
				     "<And>" +
         				"<Eq>" +
            				"<FieldRef Name='PlanningCategory' />" +
            				"<Value Type='Choice'>" + category + "</Value>" +
         				"</Eq>" +
         				"<Eq>" +
            				"<FieldRef Name='ProjectNumber' />" +
            				"<Value Type='Text'>" + pid + "</Value>" +
         				"</Eq>" +
      				"</And>" +
   				  "</Where></ViewFields></View>";

        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml(prjQry);

        this.collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
	    	Function.createDelegate(this, this.OnQuerySucceeded),
	    	Function.createDelegate(this, this.queryError)
	    );
    }
}

function OnQuerySucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var id = oListItem.get_item('ID');
        alert("In loop: " + id);  //<-- Returns '[b]In loop: 36[/b]'
    }
    alert("Outside loop: " + id);  //<-- Returns '[b]outside loop: 36[/b]'
    return id;    //<-- Should return 36 but the calling function alerts 'undefine' WHY?

}

Open in new window


Thanks!
0
Comment
Question by:Isaac
  • 3
4 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41901857
The function getId() is not returning a value.

You need to do a return of the required value from the function in order for the assignment to mean anything - otherwise how is the code supposed to know what value you want to assign to itemID?
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41901865
Line 30
var itemID = getID(itemProjectNumber, 'Procurement Plan (Design)');

Open in new window

Line 35 - 68
function getID(pid, category) {
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Project Projections');
    ...
        // ASYNC invoke - see comments below
        clientContext.executeQueryAsync(
	    	Function.createDelegate(this, this.OnQuerySucceeded),
	    	Function.createDelegate(this, this.queryError)
	    );
       // NO RETURN HERE
    }
}

Open in new window


You need to get to grips with how Asynch applications work. An asynch operation as you have above essentially means that anything that is dependent on the return from the Async function must only be called after the function returns.

You are setting up a success handler OnQuerySucceeded - in that function you are solving the itemID (Line 79) - but by this stage Line 30 is already ancient history.

You need to kick off whatever you want to do with the itemId in the success handler or you need to use a Promise - which you return from getId so itemId would be
var itemId = getId(....).then(function(data) {
   // do what you need with the return here
});

Open in new window


Bottom line - is your processing of the return from the Asynch function is disconnected from the rest of the application - so you need to change your code so that you bring them together

function OnQuerySucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var id = oListItem.get_item('ID');
        alert("In loop: " + id);  //<-- Returns '[b]In loop: 36[/b]'
    }
    alert("Outside loop: " + id);  //<-- Returns '[b]outside loop: 36[/b]'
   // This return is meaningless - it does not go anywhere and it will occur ages after line 30
   // completes.
   // Whatever you were going to do on Line 30 you must do here.
    return id;    //<-- Should return 36 but the calling function alerts 'undefine' WHY?

}

Open in new window

0
 
LVL 5

Author Comment

by:Isaac
ID: 41901877
Now that makes a lot of sense.  Looks like I need to understand scope a lot better.
I will modify my code to reflect suggested changes.

Thanks!
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41901948
You are welcome.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now