Encountered an issue while attempting to update a Sharepoint list using javascript

Recent Update

After experimenting with a new approach, I encountered an issue. The code works fine on the first call, but when attempting a second call, it throws an error stating that the collection has not been initialized. More details about this problem can be found in the comments within the test function below.

Javascript:

function test(){
    //the initial call works without issues
    countRetrieve('Very', 'Difficult');
    //the second call triggers an error regarding uninitialized collListItem
    countRetrieve('Less', 'Interesting');
}   

function countRetrieve(grade, title) {
    var siteUrl = '/sites/MySite';
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Summary');

    var camlQuery = new SP.CamlQuery();

    camlQuery.set_viewXml('<View><Query><Where>' +
    '<And>' +
    '<Eq><FieldRef Name=\'Grad\'/><Value Type=\'Text\'>' +
    grade +
    '</Value></Eq>' +
    '<Eq><FieldRef Name=\'Title\'/><Value Type=\'Text\'>' +
    title +
    '</Value></Eq>' +
    '</And>' +  
    '</Where></Query></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onRetrieveQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

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

    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        itemId = oListItem.get_id();
        itemCount = oListItem.get_item('Count');
    }
    updateCount();
}

function updateCount() {
    var clientContext = new SP.ClientContext('/sites/MySite');
    var oList = clientContext.get_web().get_lists().getByTitle('Summary');

    this.oListItem = oList.getItemById(itemId);
    //increment the count by one
    var c = itemCount + 1;
    oListItem.set_item('Count', c);

    oListItem.update();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onUpdateSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onUpdateSucceeded(sender, args){
    alert('item count successfully updated');
}

I am attempting to retrieve the current value of the "Count" column in my list and increment it by 1. However, I'm encountering an error indicating that the collection has not been initialized.

Wasn't it initialized in this.collListItem = oList.getItems(camlQuery); ?

If there are better ways to achieve this task in Sharepoint and Javascript, I would greatly appreciate any guidance as I am relatively new to both technologies.

Here is my revised code (javascript):

function countUpdate() {
    var siteUrl = '/sites/MySite';
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Summary');

    var camlQuery = new SP.CamlQuery();

    camlQuery.set_viewXml('<View><Query><Where>' +
    '<And>' +
    '<Eq><FieldRef Name=\'Grade\'/><Value Type=\'Text\'>' +
    'Really' +
    '</Value></Eq>' +
    '<Eq><FieldRef Name=\'Property\'/><Value Type=\'Text\'>' +
    'Narrow' +
    '</Value></Eq>' +
    '</And>' +  
    '</Where></Query></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onUpdateQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var count = oListItem.get_item('Count');
        oListItem.set_item('Count', '40'); //updating count to 40
        oListItem.update();
    }
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onUpdateQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}

Answer №1

The issue you are experiencing is due to the asynchronous nature of AJAX. When a call is made, other code continues to execute before the response is received. To handle this, you need a "handler" function that will be executed when the request is complete and will process the returned data.

The executeQueryAsync function requires a method called "succeededCallback" as its first parameter. You must create this method and pass it to the function without parentheses, so it is treated as a reference rather than being executed immediately. This method will automatically be called when the request is completed, with the results of the call passed as the first argument.

In your case, you will need to chain together three functions:

1) Sets up the initial call and then calls the second function upon completion.

2) Processes the results from the initial call, triggers the second call, and then calls the third function upon completion.

3) Handles the results from the second call.

You can use SharePoint's built-in functions for this, but some may find them cumbersome. Alternatively, you can create your own AJAX abstraction like the one available here:

Although the implementation may differ, the underlying concepts remain the same. Reviewing the examples provided in the link may provide clarity on how to approach your situation.

I hope this explanation helps. It's common to struggle with understanding this concept at first, but once you grasp it, everything falls into place.

Answer №2

In order to retrieve information, it is essential to proceed with the execution within the onUpdateQuerySucceeded function. Until this point, the list will remain devoid of any data as a request must be dispatched to the server and its response handled before items are obtained.

The rationale behind naming the functions as XXXXAsync is precisely for this purpose - triggering them does not yield immediate results, but rather asynchronously through a success callback.

Answer №3

Appreciate the response, Jim. Your input is not only helpful to the question owner but to others as well.

To make things easier, I have provided a sample code snippet below: This script allows you to update multiple SPListItems by simply clicking on a single CheckBox

var appOpsUrl = '/sites/AppOpsRep';
var coll;

function UpdateTargetInReport(checkBox, refValueOne, refValueTwo)
{
    // Function code goes here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using knockout to data bind a function to an onclick event that takes in multiple parameters

I've scoured the internet and experimented with various methods, but I'm encountering an issue where the click function intermittently fails to fire. Below is my HTML code snippet: <input type="radio" data-bind="checked:a, checkedValue: 0 ...

What is the best way to link the width and height of a div with form fields?

I need to implement a feature where I can create multiple div elements that are draggable and resizable, and have their properties like width, height, etc. linked to corresponding objects in an array. For example, if I create six divs, there should be six ...

React onClick event not firing

I'm new to working with React and I'm having trouble getting the onClick event to work properly. My goal is to render a modal when an icon is clicked, but for some reason the onClick event isn't responding. I've tried implementing it in ...

An issue with the canvas: The distortion of array values in Javascript causing problems when drawing on the canvas

click here for image description click here for another image descriptionI've been playing around with some JavaScript animations involving random-sized dots floating on a canvas and connecting when the distance between them is less than 150px. The co ...

Rearrange the position of the customized google map marker to appear just above the latitude

Can you provide guidance on how to move a customized Google Map marker above a specific latitude and longitude point? You can view the code structure in this JSBIN: Link. I have used three object arrays for reference. Where should I insert the "anchor" i ...

Initiate a $digest cycle externally

How can I ensure that $digest triggers when calling methods from outside Angular in an application where code is loaded and eval'd at runtime? Considering that these methods may also be called from within Angular, would it be better to expose a separa ...

What is the reason behind the "import statement error" that occurs during yup validation?

When running our code, we are encountering the following error: "Module not found: Can't resolve '@hookform/resolvers/yup'" ...

Incorporate fresh Google sites into different web pages using iFrame integration

Wishing you a fantastic day! I am currently working on embedding a brand new Google site into another webpage. I attempted to use an iframe for this purpose, but unfortunately it did not work as expected. Here is the code snippet: <iframe width="1280 ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

React.js implementation of individual checkboxes for every row in a table

My functional component contains a table with multiple rows as shown below: import React from "react"; import Checkbox from "@material-ui/core/Checkbox"; function Table({ data }) { const [checked, setChecked] = useState(false); ...

Tips for eliminating null values from a JavaScript object

I am currently facing an issue with a JavaScript object that consists of two arrays. At times, one of the arrays might be empty. I am attempting to iterate through the object using a recursive function, but I want to exclude any empty arrays or strings fro ...

Leveraging dynamic keys with v-for in Vue.js

In my Vuejs project, I am currently developing a reusable table component that looks like this: Table Component Structure: <template> <div> <table class="table"> <thead> <tr> ...

A guide to setting an href using variable values in jQuery through manual methods

I have a datepicker set up where each day, month, and year is stored in a variable. I then display this information in the desired format. Below is the jQuery code: jQuery(document).ready( function($){ alert('alert function'); var txtFr ...

What is the best way to extract these components by utilizing a function rather than directly embedding them into the code?

I am attempting to reduce the amount of code inside the return statement by creating a separate method for it, as shown in the second image. However, I am facing an issue where only the h4 tag is being displayed without any of the input fields. Original C ...

Is there a way to gradually reveal JSON data without continuously re-parsing and displaying it on a webpage?

Currently, I am working with a log file that is constantly updated by a running script in real-time. My goal is to effectively monitor the status of this script on a web page using HTML and JavaScript. To achieve this, I have utilized JavaScript to dynamic ...

Can I relocate myself to the background in Node.js?

Although I am aware of this reference, it unfortunately doesn't address the specific question I have. I'm currently developing a Node.JS application to manage multiple Steam trade bots, and I'm in the process of adding a terminal-like inter ...

Receiving undefined properties in functional React components

Is it possible to pass the {requests} prop to the RequestRow component correctly, especially after the setRequests function is executed? The issue seems to be that when requests are initialized as undefined initially and then set with an asynchronously cal ...

Oops! React js material-table is throwing a TypeError because it's having trouble converting undefined or null to

{ title: 'Stores', field: 'Depolar', editComponent: props => ( <Select name="Depolar" type="text" value={that.state.selectedStores} multiple inp ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...

Create an interactive webpage that automatically generates new HTML elements after retrieving JSON data from a Web API during page load

I am currently in the process of developing a hybrid Android App using Phonegap/Apache Cordova. The main function of my app is to retrieve data from my web API, which is being served through JSON. I have implemented the following code snippet for this task ...