Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

JavaScript Scope issue

Posted on 2016-11-25
4
Medium Priority
?
77 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
  • 3
4 Comments
 
LVL 60

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 60

Accepted Solution

by:
Julian Hansen earned 2000 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 60

Expert Comment

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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
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…
Suggested Courses

926 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