1

I am developing a visual web part and I am trying to some list items on demand. With this in mind I have created a WebService named CommentFetchSvc.asmx and added the following code:

public class CommentFetchSvc : System.Web.Services.WebService
{
    public CommentFetchSvc()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    public class BlogItem
    {
        public string Title { get; set; }
        public string Body { get; set; }
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<BlogItem> ReadComments(string pagenum)
    {
        List<BlogItem> blogList = new List<BlogItem>();

        using (SPSite oSpSite = new SPSite("http://mysiteUrl"))
        {
            using (SPWeb oSpWeb = oSpSite.OpenWeb())
            {
                SPList oList = oSpWeb.Lists["LageData"];
                SPQuery oQuery = new SPQuery();

                int pageNum = int.Parse(pagenum);
                // Number of rows to fetch
                oQuery.RowLimit = 5;

                // Start reading from 1
                int intIndex = 1;
                do
                {
                    SPListItemCollection collListItems = oList.GetItems(oQuery);

                    // Check if this are the records to be returned
                    if (intIndex == pageNum)
                    {
                        // Read items for the specific range
                        foreach (SPListItem oListItem in collListItems)
                        {
                            BlogItem item = new BlogItem();
                            item.Title = oListItem["Title"].ToString();
                            item.Body = oListItem["ID"].ToString();
                            blogList.Add(item);
                        }
                        break;
                    }
                    oQuery.ListItemCollectionPosition = collListItems.ListItemCollectionPosition;
                    intIndex++;
                }
                while (oQuery.ListItemCollectionPosition != null);
            }
        }
        return blogList;
    }
}

I created and sent WebService in _layouts/15/Load5MoreComments. When I enter the url of WebService it loads successfully and I can see my methods: webservice

then I am trying to call ReadComments from ajax with following code:

<asp:HiddenField Value="1" id="pageTrack" runat="server"></asp:HiddenField>
<script type="text/javascript">       
$(document).ready(LoadData());

function LoadData() {
    GetCommentItems();
}

function GetCommentItems() {
    var pageTrack = $("input[id$='pageTrack']").val();
    $.ajax({
        url: "/_layouts/15/Load5MoreComments/CommentFetchSvc.asmx/ReadComments",
        type: "POST",
        data: "{'pagenum':'" + pageTrack + "'}",
        contentType: 'application/json;',
        dataType: 'json',
        success: function (msg) {
            AppendItems(msg);
            var newPageTrack = $("input[id$='pageTrack']").val();
            $("input[id$='pageTrack']").val(parseInt(newPageTrack) + 1);
        },
        error: function (xhr, msg) {
            console.log(msg + '\n' + xhr.responseText);
        }
    });

    function AppendItems(data) {
        $.each(data.d, function (i, item) {
            var title = item.Title;
            var body = item.Body;
            html = '<li><b>' + title + '</b></li>';
            html += body;
            html += '<hr/>';
            $('#resultarea').append($(html));
        });
    }
}
</script>

 <p>

<asp:HyperLink NavigateUrl='javascript:void(0);' id="lnkMore" onClick="GetCommentItems();" runat="server">View next five comments..</asp:HyperLink>
</p>

BUT I AM GETTING THE FOLLOWING ERROR Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Although when I click ReadComments link in my WebService from the browser it works perfect and when I fill the pagenum parameter it shows my data. But AJAX won't call the method. webservice

When I enter 1 in my pagenum parameter: enter image description here

Please HELP ME.

1 Answer 1

2

It's a SOAP Service, so try sending XML instead of JSON. Something like:

$.ajax({
  url: "/_layouts/15/Load5MoreComments/CommentFetchSvc.asmx",
  type: "POST",
  dataType: "xml",
  beforeSend: function(xhr) { xhr.setRequestHeader('SOAPAction', 'http://tempuri.org/ReadComments'); },
  data: '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ReadComments xmlns="http://tempuri.org"><pagenum>'+pageTrack+'</pagenum></ReadComments></soap:Body></soap:Envelope>',
  contentType: 'text/xml; charset=utf-8',
  success: function (msg) {
    console.log(msg)
  },
  error: function (xhr, msg) {
    console.log(msg + '\n' + xhr.responseText);
  }
});
9
  • Thanks for you answer but I am getting the following error: error Request format is invalid: text/xml; charset=UTF-8. I changed to following line to return XML [ScriptMethod(ResponseFormat = ResponseFormat.Xml)] Oct 9, 2017 at 7:40
  • I've updated my answer by changing the endpoint url and by adding ` dataType`. Try with them. If it still doesn't work, then I don't know, because this is how to deal with the standard Sharepoint SOAP services.
    – AymKdn
    Oct 9, 2017 at 12:15
  • I am getting a new error: Unable to handle request without a valid action parameter. Please supply a valid soap action. Oct 9, 2017 at 12:22
  • Sorry I misread the screen capture. You also need to add a header SOAPAction to your request. See my edited answer. All of these things are explained when you go to /_layouts/15/Load5MoreComments/CommentFetchSvc.asmx/ReadComments
    – AymKdn
    Oct 9, 2017 at 12:28
  • thanks for your comment but I am getting again a new error: Server was unable to process request. ---&gt; Value cannot be null. Parameter name: String Oct 9, 2017 at 13:10

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.