0

I have the following page method in the file default.aspx.vb, using .NET 2.0:

<WebMethod()> _
Public Shared Function GetStatisticData(ByVal userId As Integer) As JavaScriptSerializer
    Dim stats As JavaScriptSerializer = New JavaScriptSerializer()

    stats.Serialize(statBiz.GetAllSaleStatistics(userId))

    Return stats
End Function

And in default.aspx

opt.ajax({
    type: "POST",
    url: 'default.aspx/GetStatisticData',
    data: "{userId: 6601}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log(data);
    },
    error: function (request, status, error, response) {
        console.log(error);
    }
});

But the method in the codebehind file does never get hit and i get this error from the console log:

SyntaxError: Unexpected token < in JSON at position 2
    at JSON.parse (<anonymous>)
    at n.parseJSON (jquery-1.12.4.min.js:11)
    at Xb (jquery-1.12.4.min.js:11)
    at y (jquery-1.12.4.min.js:11)
    at XMLHttpRequest.c (jquery-1.12.4.min.js:11)

Can somebody tell me what I am missing here?

6
  • Do you have a ScriptServiceAttribute decorating your WebService's class? Commented Feb 19, 2018 at 21:26
  • Please/check post the server response (if a request is actually being made of course stackoverflow.com/q/43363866/397817 A tool like Fiddler is a great help. Commented Feb 20, 2018 at 2:16
  • Also, what version of .NET are you using? Commented Feb 20, 2018 at 11:34
  • This is an old application on .net 2.0 Commented Feb 20, 2018 at 12:22
  • Can you post in the server response? I have a feeling it is XML. And it is possible to target .NET 3.5? (same CLR as 2.0 but with extra features and bug fixes). Commented Feb 20, 2018 at 12:44

2 Answers 2

1

Can somebody tell me what I am missing here?

For starters your return type should be the return type of statBiz.GetAllSaleStatistics and should return the result of that call. You do NOT need to spin up a serializer yourself and there is no need to tie yourself to returning JSON when the Framework is capable of determining which serializer to spin up based on the request headers. You certainly shouldn't try to return a JavaScriptSerializer.

This sample code and output should demonstrate why returning the serializer won't work:

Dim js = New JavaScriptSerializer()
js.Serialize(New List(Of Int32) From { 1, 2, 3})
Console.WriteLine(New JavaScriptSerializer().Serialize(js))

{"MaxJsonLength":2097152,"RecursionLimit":100}

That's not a serialized list! It's a serialized serializer!


Let's say for the purpose of illustration that statBiz.GetAllSaleStatistics(userId) returns an instance of a SaleStatistics class. Please try the following but of course replace SaleStatistics with your actual type:

<WebMethod()> _
Public Shared Function GetStatisticData(ByVal userId As Integer) As SaleStatistics
    Return statBiz.GetAllSaleStatistics(userId)
End Function

This in itself will likely not wholly resolve your issue. I have a suspicion that your method is returning XML and that being a legacy app there may be entries missing from web.config. You may also need to target .NET Framework 3.5.

Sign up to request clarification or add additional context in comments.

1 Comment

I return a list of Statistic but my method is never hit when i run in debug mode and when I tjek the result of error and response I get 1. parsererror Error : SyntaxError: Unexpected token < in JSON at position 2 2. undefined
0

Webmethods are used by webservices, not web applications. You install the webservice on a server and call (SOAP) the webservice in your code after adding the web service as a service. The extension for a webservice file is .asmx. Web services are kind of dated (.NET Framwork 2.0 to 3.5) and most folks use RESTful api's. To create a web service go to File --> New -->Asp.Net Empty Web application. on that Right click --> Add New item - >webservice template.

Now if you do not like that answer and still want to use your code, remove the webmethod_ from your code and in javascript you can assign the results of the call to a variable using '<%= GetStatisticData(SomeVariableStoringUserID) %>' passing in the userid you're querying.

UPDATE: Seems as if I'm behind the times a bit, to say the least. So @Stephen Kennedy answer would seem to be the correct one in this context. Your method returns JavaScriptSerializer when I think you're expecting a json document.

5 Comments

I think you've got the wrong end of the stick here :) He has a page method, which is a web method declared in code behind. It's almost identical to asmx except the method is declared as static/shared in the .aspx.vb. He is calling the web method with a jQuery Ajax call. Page methods are capable of returning JSON when properly configured and called correctly. Yes this is legacy tech, but it is something that ought to work. Moving to asmx likely won't make any difference, and the inlining suggestion is irrelevant here as this is not webform output but an Ajax call.
I'm not familiar with Ajax so I cannot comment. I'm a tad old school but I've never seen a webmethod used in this context anywhere. It has always been my understanding that webmethods are called via SOAP, I do not see any indication that SOAP is in use here.
The JSON capabilities were retro-fitted by Microsoft (in Framework 3.5 from the best I can tell/remember). Call an ASP.NET C# Method (Web Method) Using JQuery is a nice intro. We have this in production use alongside some SOAP and a growing ASP.NET Web API and we're far from alone in that.
Thanks for the info, I do admit I'm a tad behind with all the latest techniques. Last 10 years of my career was as a Systems Engineer and I've been retired for 2 years. So I'm behind just a little ... lol ...
Calling the method directly works just fine, but as I need to call this with ajax it has to work that way ;o)

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.