1

I have a webmethod returning an object and I am having difficulty accessing the object returned from the jQuery Ajax method. I would like to access the HighlightResults and display in a repeater. I keep getting the error: There was an error processing the request. Internal server error.

My object is:

  public class SearchResults
  {
    internal SearchResults()
    {

    }

    public virtual IQueryable<Document> DocumentResults { get; internal set; }
    public virtual IQueryable<Page> PageResults { get; internal set; }
    public virtual IQueryable<Word> WordResults { get; internal set; }
    public ICollection<String> HighlightResults { get; internal set; }
    public int QueryTime { get; internal set; }
    public int TotalResults { get; internal set; }

}

And my ajax function:

var query = String($('[id$=txtSearch]').val());            
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Viewer.aspx/GetHighlightResults",
            dataType: "json",
            data: JSON.stringify({docID: docid, query: query, 
                  pageNumber: 1, resultsPerPage: 10}),
            success: function (response) {
                alert("Success!!");                 
                var data = response.d;

                // none of these are displaying....
                alert(String(data));
                alert(String(data.HighlightResults));
                alert(String(data.HighlightResults[0]));

                $.each(data, function(index, item) {
                    alert(item);
                    alert(item.HighlightResults);

                    $("#search-results").append("<b>" + item + "</b>");
                })
            },
            error: function (xhr, status, error) {
                alert("responseText=" + xhr.responseText + 
                      "\n textStatus=" + status + "\n errorThrown=" + error);
            }
        });

And finally, my web method:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static SearchResults GetHighlightResults(String docID, String query, 
                  String pageNumber, String resultsPerPage)
    {
        SearchResults results = null;
        try
        {
            ArchiveSearcher searcher = new ArchiveSearcher();
            if (!String.IsNullOrEmpty(query) && Convert.ToInt32(docID) > 0 && 
                Convert.ToInt32(pageNumber) > 0 && Convert.ToInt32(resultsPerPage) > 0)
            {
                results = searcher.SearchDocument(Convert.ToInt32(docID), query, 
                Convert.ToInt32(pageNumber), Convert.ToInt32(resultsPerPage)); 
            }
        }
        catch (Exception ex)
        {
            // Log the exception.
            ArchiveViewer.Logic.ExceptionUtility.LogException(ex, "GetSearchResults in Viewer.aspx.cs");
        }
        return results;
    }

Help is appreciated.

EDIT: If I return the ICollection<String> Highlight results from the web method, I can access it from the jquery ajax function using:

success: function (response) {
    var data = response.d;
    $.each(data, function(index, item) {
         alert(item);
....

I think my issue is related to how I access the entire SearchResults object. Any ideas as to what I'm doing wrong?

EDIT 2: I've commented out everything in my ajax success function and it still fails. So the issue is with passing back the class. Any ideas?

7
  • Does it hit the webmethod if you debug? Commented Jan 27, 2014 at 10:41
  • Yes, and I am returning something. But it doesn't hit alert("Success!!"); I get the error instead. Commented Jan 27, 2014 at 10:46
  • It looks like it. I'm getting the following: Failed to load resource: the server responded with a status of 500 (Internal Server Error) localhost:5148/Viewer.aspx/GetSearchResults Commented Jan 27, 2014 at 10:53
  • Then it does not hit your function...try to change your data to only one and pass that to function with one parameter.. Commented Jan 27, 2014 at 10:57
  • Perhaps this is a silly question but, if it hits my breakpoint in my webfunction, then how is it not hitting it? Also, see edit above. If I return collection<string> it works fine. Commented Jan 27, 2014 at 11:01

4 Answers 4

1

Ahhh!!! I figured it out. Thank you Zaki, you nudged me in the right direction!!

I didn't have any errors in the web method, but exception occurred when my object was being serialized to JSON. The issue is with serializing IQueryable<T> in my class. I've changed it to List<T> and everything is working now. (A day of my life gone!)

Just to be complete, the correct way to access the objects being returned in the client is:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Viewer.aspx/GetSearchResults",
    dataType: "json",
    data: JSON.stringify({ docID: docid, query: query, pageNumber: 1, resultsPerPage: 10 }),
    success: function (response) {
        var data = response.d.HighlightResults;
        $.each(data, function (index, item) {
            $("#search-results").append("<b>" + item + "</b>");
        })
    } 
......
Sign up to request clarification or add additional context in comments.

1 Comment

I missed : contentType: "application/json; charset=utf-8" - thanks
0

Through Jquery ajax you pass the JSON.stringify data but in your method you get it as a normal string

Check with that reference link https://stackoverflow.com/a/6323528/2641723

1 Comment

I know that the way I pass in the data is correct. I do the same thing in another method. I'm pretty sure my issue is with retrieving and accessing the data.
0

I did the same thing in a test project and it returned success. I can see the alert firing:

here is what I changed in object:

  public virtual IQueryable<string> DocumentResults { get; internal set; }
  public virtual IQueryable<Page> PageResults { get; internal set; }
  public virtual IQueryable<string> WordResults { get; internal set; }

then in ajax :

  data: JSON.stringify({
                docID: 'test',
                query: 'tet2',
                pageNumber: 1,
                resultsPerPage: 10
            }),

and :

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static SearchResults GetHighlightResults(String docID, String query,
                      String pageNumber, String resultsPerPage)
        {
            SearchResults results = null;
            try
            {
                 results = new SearchResults();
            }
            catch (Exception ex)
            {
                // Log the exception.
                //ArchiveViewer.Logic.ExceptionUtility.LogException(ex, "GetSearchResults in Viewer.aspx.cs");
            }
            return results;
        }

I suggest you check that there are not any exceptions in the webmethod.

1 Comment

I need to send back my custom classes (Document, and Word). Unfortunately, string is not enough. :(
0

I faced similar issue , posting my solution :

jsp file :

<c:forEach var="myMap" items="${myMap}" varStatus="status">
        <tr><td>
                ${myMap.key}
            <c:forEach var="info" items="${myMap.value}">
                URL ${info}
                <select id="dropdown" name="dropdown">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>

                </select>
                <button type="button" onclick="test()">Update</button>

            </c:forEach>
        </td></tr>
    </c:forEach>

Controller file :

 @RequestMapping(value = "postData", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public String putService(@RequestBody HashMap<String, String> myMap) {
 // perform operations  
  return String;
}

js file:

function test(){
    $.ajax({
        url: 'your url',
        type: 'PUT',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify({"Key":"Value"}),
        success: function(data) {
            alert('Operation Success');
        }
    });

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.