So, as the title suggests, i'm using SP Services to get data from the "Comments" List. I can retrieve the data fine but i'm trying to limit what is returned to only the top (Let's say 5) comments by submitted date. This is what I have

but the if statement doesn't work;

function getID2(valID) {

        var cmtotal = Number(valID.split('-')[1]);
        valID = Number(valID.split('-')[0]);

        if (cmtotal <= 0) {
        } else {

            var EVENTID = Number(valID);
            var method = "GetListItems";
            var webURL = $().SPServices.SPGetCurrentSite();
            var list = "Comments";
            var fieldsToRead = "<ViewFields>" + "<FieldRef Name='Name' />" + "</ViewFields>";
            var query = "<Query><OrderBy><FieldRef Name='ID'  Descending='True' /></OrderBy></Query>";
            var i = 0;
            var max = 5;
                operation: method,
                async: false,
                webURL: webURL,
                listName: list,
                CAMLViewFields: "<ViewFields Properties='True' />",
                CAMLQuery: query,
                completefunc: function(xData, Status) {
                    $(xData.responseXML).SPFilterNode("z:row").each(function() {
                        if (i == max + 1) {
                        } else {
                            var cID = Number($(this).attr("ows_EventID").split("#")[1]);
                            if (EVENTID == cID) {
                                var auth = $(this).attr("ows_Author").split("#")[1];
                                var body = $(this).attr("ows_Body");
                                    '<div class="container-fluid">' +
                                    '<div class="col-xs-2" style="text-align: right">' + auth + ':</div>' +
                                    '<div class="col-xs-10"><div class="well" style="text-align: left">' + body + '</div></div>' +


I think your issue is the scope of your variable "i" which you are incrementing inside the function which gets called on each row and gets its own copy of "i" each time.

Put an alert displaying "i" and you will see what I mean.

Why not use

 CAMLRowLimit: 5

In your SPServices call - it should do all that for you.


Better you can write your query like this:

var query = "<Query><OrderBy><FieldRef Name='ID'  Descending='True' /></OrderBy><RowLimit>5</RowLimit></Query>";

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.