1

I have a list column which I want to update using JSOM on button click. Here's my code -

function updateListItem() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('Topics');
this.oListItem = oList.getItemById(20);
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
var oldData = oListItem.get_item('ViewCount');
var newData = parseInt(oldData) + 1;
alert(newData);
oListItem.set_item('ViewCount', newData);
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onItemUpdated), Function.createDelegate(this, this.onQueryFailed));
}

function onItemUpdated() {
   alert('Item has been updated!');
}

function onQueryFailed(sender, args) {
    alert('Request failed.');
}

But, it's not working.

1

To get the properties of List item you have to query the server by calling ExecuteQueryAsync. So it can be like this:

clientContext.load(
        oListItem,
        'Include(Id, DisplayName, HasUniqueRoleAssignments,ViewCount)'
    );
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
  • I've updated my code as per your suggestion. But, it's still not working. – Korak Jul 18 '17 at 6:48
0

You are trying to access field ViewCount before executeQueryAsync.

So your code oListItem.get_item('ViewCount'); will fail in updateListItem function.

'executeQueryAsync'Executes the current pending request asynchronously on the server.

No communication occurs with the remote server until you call ExecuteQuery or ExecuteQueryAsync (in this case 'ExecuteQueryAsync').

So you will not be able to access the value of field ViewCount in updateListItem function. But the value will accessible in success Handler.

And after getting this value in success function, you will have to make another request the list to update the value of that field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.