0

I have two lists 'a' and 'b' with same titles but different ids. I retrieve the title from 'a' list to a html page. And, there is a 'b' list. Here, both the lists have different ids but has same titles (same items). I have created a variable count to increment the count value in Count column in b list. Now my idea is to update the count value of that clicked item from the html page in the 'b' list. Any solutions/ suggestions or help from you would be greatly appreciated!

Retrieving the title from 'a' list to a html page:

function xyz() {

    var resturl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('a')/items?$top=1000";

    $.ajax({

        url: resturl,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },

        success: function (data) {

            var lnt = data.d.results.length;
            var name = "";
            var cntlnks = "";
            var iconurl = "";

            for (var i = 0; i < lnt; i++) {

                if (data.d.results[i].Title == "MGT") {
                    name = data.d.results[i].Name;
                    itemid = data.d.results[i].ID;
                    cntlnks = data.d.results[i].ContentLinks;
                    iconurl = data.d.results[i].Iconurl;
                  
                    if (data.d.results[i].Phasenumber == 1) {
                        if (data.d.results[i].Phasegroup == "g") {

                            $("#mgd1").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems" ><a href=' + cntlnks + ' target="_blank"  onclick="myFunc(this);" value="' + name + ' ' + itemid + '">' + name + '</a></p></div></ br>')
                        }

                        if (data.d.results[i].Phasegroup == "t") {
                            $("#mgt1").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }

                        if (data.d.results[i].Phasegroup == "s") {
                            $("#mgs1").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }
                    }
                    if (data.d.results[i].Phasenumber == 2) {
                        if (data.d.results[i].Phasegroup == "g") {

                            $("#mgd2").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }

                        if (data.d.results[i].Phasegroup == "t") {

                            $("#mgt2").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }

                        if (data.d.results[i].Phasegroup == "s") {

                            $("#mgs2").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }
                    }
                    if (data.d.results[i].Phasenumber == 3) {
                        if (data.d.results[i].Phasegroup == "g") {
                            $("#mgd3").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }

                        if (data.d.results[i].Phasegroup == "t") {
                            $("#mgt3").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }

                        if (data.d.results[i].Phasegroup == "s") {
                            $("#mgs3").append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a href=' + cntlnks + ' target="_blank">' + name + '</a></p></div></ br>')
                        }
                    }
                }
            }
        },

        error: function (data) {
            console.log(data.responseJSON.error);
        }
    });
}


function myFunc(lnk) {
    let val = lnk.getAttribute('value');   
    console.log(val);
    updateItems(val);
}

Updating list item count value in b list:

var count = 0;

function updateItems() {

count = count + 1;

var resturl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('b')/getItemById(1)";
var itemType = GetItemTypeForListName('b');

    $.ajax({
           url: resturl,
           type: "POST",
           data: JSON.stringify({'__metadata': { 'type': itemType }, 'Count': count }),
           headers: {
           "accept":"application/json;odata=verbose",
           "content-type": "application/json;odata=verbose",
           "X-RequestDigest":$("#__REQUESTDIGEST").val(),
           "X-HTTP-Method": "MERGE",
           "IF-MATCH":"*"
            },
            
    success: onSuccess,
    error: onError
    });

   function onSuccess(data) {
   alert('List Item Updated');
   }

   function onError(error) {
   alert(JSON.stringify(error));
   }

   function GetItemTypeForListName(name) {
   return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
   }
}

4
  • So what field in list b matches the Name field from list a? Is there also a Name field in list b, or does Name from list a match the Title field in list b? Feb 17, 2021 at 17:36
  • Sorry! In List 'a', it has Name field and in List 'b', it has Title field. But it has same items in both lists, only column names were different
    – Venkat Sai
    Feb 17, 2021 at 17:42
  • Ok. And also, you need to record the click count, but you also need the <a> link to actually go to the href URL (ContentLinks)? Feb 17, 2021 at 17:46
  • Exactly.. On clicking that <a> link, it shows doc in new tab. So there are 9 <a> tags, it should record click count for each <a> when clicked on that respective <a> link
    – Venkat Sai
    Feb 17, 2021 at 17:52

1 Answer 1

1

In order to update the item from list 'b', you need to know the item ID of the item in list 'b'. But - that is not necessarily going to match the item ID of the matching item from list 'a'. In the comments, what you have said is that the value of the Title field in list 'b' is what is going to match the value of the Name field from the items in list 'a'.

Great, we can definitely work with that.

Now, first I'd change your link setup a bit. You don't need to add the ID of the item from list 'a' into any attribute on your links, because that ID is not going to do you any good unless you need to access the item in list 'a', which you don't, you're trying to update the item in list 'b'. And you're already using the value of the Name field as the text of the link, so you don't need to add that to any attribute either. Also, since you are using jQuery, instead of adding an onclick attribute directly on the <a> elements, why not use jQuery to add a click handler to all the links at the same time after you are done rendering them?

for (var i = 0; i < lnt; i++) {

    if (data.d.results[i].Title == "MGT") {

        // your other logic still goes here

        // when you append your link, add a class to the <a> element

        $('yourSelector').append('<div class="rowAlign"><img src= ' + iconurl + ' class="groupingIcon" /><p class="listedItems"><a class="myAnchor" href="' + cntlnks + '" target="_blank">' + name + '</a></p></div><br/>')
    }
}

// now that the for loop is done, you know you have
// added all the links you are going to add, so then use 
// jQuery to add a click handler to all of them at the same time

$('a.myAnchor').click(function() {
    // you already have the value of the "Name" field
    // as the text of the anchor element
    var name = $(this).text();
    updateClickCount(name);
});

So now when any of your links are clicked, you are sending the Name value into a function updateClickCount(), where you can use that value to find the matching item from list 'b'. When you get the matching item from list 'b', it will give you two very important things:

  • The ID of the item in list 'b' which you can use to build the URL you need to update the item.
  • The currently stored Count value, which you need to know if you are going to increment it by one and update it back to the list item.

Since you need to first get the matching item, then update it, the updateClickCount() function might look something like this:

function updateClickCount(matchingName) {

    // in order to get the item who's Title matches the "Name" value
    // passed into the function, you need to add a "filter" to the REST query

    var getItemUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('b')/items?$filter=Title eq '" + matchingName + "'";

    // this query will get any and all items who's Title matches the filter criteria,
    // so you may end up with zero results, or more than one result

    $.ajax({
        url: getItemUrl,
        method: 'GET',
        headers: {
            accept: 'application/json;odata=verbose'
        }
    }).done(function(getItemData) {

        // see how many matches came back
        var resultCount = getItemData.d.results.length;

        if (resultCount === 0) {
            // no mathcing items found
            alert('Uh oh! No items found in list b with a Title of ' + matchingName);
        } else if (resultCount > 1) {
            // multiple matching items found
            alert('Uh oh! Found ' + resultCount + ' items in list b that have a Title of ' + matchingName);
            console.log(getItemData.d.results);
        } else {
            // single matching item found
            var itemID = getItemData.d.results[0].ID;
            var currentCount = getItemData.d.results[0].Count;

            // increment the count
            var newCount = currentCount + 1;

            // build what you need to do the update
            var updateUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('b')/items(" + itemID + ")";
            var itemType = GetItemTypeForListName('b'); 

            // do the update
            $.ajax({
                url: updateUrl,
                method: 'POST',
                headers: {
                    "accept":"application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                    "X-RequestDigest":$("#__REQUESTDIGEST").val(),
                    "X-HTTP-Method": "MERGE",
                    "IF-MATCH":"*"
                },
                data: JSON.stringify({
                    '__metadata': { 'type': itemType },
                    'Count': newCount
                })
            }).done(function(updateData) {
                // successful update
                alert('Item updated!');
            }).fail(function(jqXhr, status, err) {
                alert('Error trying to update item from list b with ID: ' + itemID);
                console.log(status, err);
                console.log(jqXhr);
            });
        }
    }).fail(function(jqXhr, status, err) {
        alert('Error trying to get item from list b with Title: ' + matchingName);
        console.log(status, err);
        console.log(jqXhr);
    });
}

If you are having trouble seeing results, add some console.log or alert lines inside the click handler function and inside the updateClickCount function so you can follow the code progress and make sure everything is hooked up and working:

$('a.myAnchor').click(function() {
    
    var name = $(this).text();

    console.log('link clicked:', name);

    updateClickCount(name);
});

function updateClickCount(matchingName) {

    console.log('updateClickCount called with name:', matchingName);

    var getItemUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('b')/items?$filter=Title eq '" + matchingName + "'";
    $.ajax({
        url: getItemUrl,
        method: 'GET',
        headers: {
            accept: 'application/json;odata=verbose'
        }
    }).done(function(getItemData) {

        console.log('get item response:', getItemData);

        // etc.
    })
}
7
  • Thank you so much for taking some time to explain the solution, sir. I clearly understood the solution you gave. So, what I have done is.. I added class in <a> and included jquery function after for loop and also removed on click in <a>. Then copied updatecount function as it. But so sorry to say this, I see nothing here. I don't have clue what I missed. Is there any alternative way to help me other than here sir?
    – Venkat Sai
    Feb 17, 2021 at 20:21
  • I'm not sure I understand what you mean by "I see nothing here". If you copied the function, did you try it out? Were there any error messages or anything? Feb 17, 2021 at 20:26
  • No alerts are triggered sir.. not even one
    – Venkat Sai
    Feb 17, 2021 at 20:29
  • 1
    Added some suggestions to help debugging. Feb 17, 2021 at 20:43
  • Thank you for those suggestions. I'm able to get all the values using consoles but the count part is not incrementing at all and also updateData function is mentioned but has no operation in it and returns nothing.
    – Venkat Sai
    Feb 17, 2021 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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