[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 83
  • Last Modified:

JavaScript Scope issue

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
Isaac
Asked:
Isaac
  • 3
1 Solution
 
Julian HansenCommented:
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
 
Julian HansenCommented:
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
 
IsaacSharePoint Client Side DeveloperAuthor Commented:
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
 
Julian HansenCommented:
You are welcome.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now