Solved

JavaScript Scope issue

Posted on 2016-11-25
4
61 Views
Last Modified: 2017-01-31
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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 56

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 56

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 56

Expert Comment

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

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

733 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