mbauer
mbauer

Reputation: 344

Accessing SharePoint list with JavaScript Variable Storage

i started yesterday with javascript and i'm trying to get some information from a sharepoint 2010 list and i want print it into a table. the following code is in the body tag:

<script type="text/javascript">
    ExecuteOrDelayUntilScriptLoaded(mainFunction, "sp.js");
    var typeNumber = "1520";
    var statusArray = new Array(3);
    try {
        function mainFunction() {
            var clientContext = new SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle('Projektstatus');

            //empty Query string cause there are some problems with a lookup field
            var emptyCamlQuery = new SP.CamlQuery();

            this.collListItem = oList.getItems(emptyCamlQuery);
            clientContext.load(collListItem);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
            document.write(statusArray[2]);
        }

        function onQuerySucceeded(sender, args) {
            var listItemInfo = '';
            var i = 0;
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                if (oListItem.get_item('Title').match(typeNumber)) {
                    statusArray[i] = oListItem.get_item('KPI_Status');

                    //Works fine
                    alert("nummer:" + i + statusArray[i]);

                    i++;
                }
            }
        }
        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }

        var tableOutput = "<table><tr><th>Indikatortyp</th><th>KPI-Status</th></tr>" +
                        "<tr><td>Kosten</td><td>" + statusArray[2] + "</td></tr>" +
                        "<tr><td>Technik</td><td>" + statusArray[1] + "</td></tr>" +
                        "<tr><td>Termin</td><td>" + statusArray[0] + "</td></tr>" +
                    "</table>"
        document.write(tableOutput);
    } catch (e) {
        alert(e);
    }
</script>

the output with the alert works fine but when i want to print the statusArray in the table this doesn't work cause the variable is undefined. i think the problem could be something with createDelegate().

Upvotes: 0

Views: 1826

Answers (1)

Salvatore Di Fazio
Salvatore Di Fazio

Reputation: 715

The problem is because you use a global variable statusArray and your code that create the table is outside the onQuerySucceeded.

My suggestions are: - encapsulate the statusArray variable - move the creation of the table inside the onQuerySucceeded

Upvotes: 1

Related Questions