michael marmah
michael marmah

Reputation: 147

Having strange {"d":null} in JSON response

Please am doing a AJAX call to a web API as below

$.ajax({
         type: "POST",
         url: "CustomerService.asmx/GetAccounts",
         data: '{"custid":"' + cusID + '"}',
         contentType: "application/json; charset-utf-8",
         dataType: "json",
         success: function (data) {
             datatableVariable = $('#dtAccounts').DataTable({.......

This is my ASP.NET Web Method

<WebMethod()>
Public Sub GetAccounts(ByVal custid As Integer)


    Dim sql As String = "Select * from Accounts WHERE CustomerID =" & custid & " Order by ID"

    Dim constr As String = ConfigurationManager.ConnectionStrings("flashCon").ConnectionString
    Dim accs = New List(Of Accounts)()
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(sql)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Dim dr = cmd.ExecuteReader()
            If dr.HasRows Then
                While dr.Read
                    Dim acc = New Accounts() With {
                   .custID = Convert.ToInt32(dr("CustomerID").ToString()),
                    .AccNum = dr("AccountNumber").ToString(),
                    .Descri = dr("Description").ToString(),
                    .CurrBalance = dr("CurrentBalance").ToString(),
                    .typOA = dr("TypeOfAccount").ToString(),
                    .Frozen = dr("Frozen").ToString()
                    }
                    accs.Add(acc)
                End While
            End If
        End Using
    End Using
    Dim js = New JavaScriptSerializer()
    Dim strResponse As String = js.Serialize(accs)
    Context.Response.Write(strResponse)
End Sub

The JSON string response returned is the below with additional strange {"d":null} value that I dont know where its coming from

[{"custID":2,"AccNum":"KODSW00002","Descri":"","CurrBalance":0,"Frozen":false,"typOA":0}]{"d":null}

If I use Context.Response.Flush() it disappears but then I get another error from the browser Server cannot clear headers after HTTP headers have been sent.

Please can someone assist me to resolve this,been doing this for weeks now

Thanks a lot

Upvotes: 5

Views: 6078

Answers (4)

jafarbtech
jafarbtech

Reputation: 7015

We have to clear the default response {d:null} from ASP.NET Webservice before giving the response on the server side by using Context.Response.Clear() and set the contentType

Context.Response.Clear()
Context.Response.ContentType = "application/json"
Context.Response.AddHeader("content-length", stringJSON.Length.ToString())
Context.Response.Flush()
Context.Response.Write(stringJSON)
HttpContext.Current.ApplicationInstance.CompleteRequest()

Upvotes: 2

Luis Carrera
Luis Carrera

Reputation: 11

Try This

$.ajax({
     type: "POST",
     url: "CustomerService.asmx/GetAccounts",
     data: {custid: cusID},
     dataType: "json",
     success: function (data) {
         alert(data.d); // Should correctly get the response in the d variable.

The secret is that JavaScriptSerializer does not need contentType: "application / json; charset-utf-8",

and in the data the parameters go without apostrophes or double quotes are written directly

more info in: https://www.youtube.com/watch?v=Zq_aMDFeCCA

regards

Upvotes: 1

Sonu K
Sonu K

Reputation: 2802

You are getting {"d":null} because your WebMethod has no return value, you are just writing to the Response object.

You should return a string from your method:

Public Sub GetAccounts(ByVal custid As Integer) As String

Dim sql As String = "Select * from Accounts WHERE CustomerID =" & custid & " Order by ID"

Dim constr As String = ConfigurationManager.ConnectionStrings("flashCon").ConnectionString
Dim accs = New List(Of Accounts)()
Using con As New SqlConnection(constr)
    Using cmd As New SqlCommand(sql)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        con.Open()
        Dim dr = cmd.ExecuteReader()
        If dr.HasRows Then
            While dr.Read
                Dim acc = New Accounts() With {
               .custID = Convert.ToInt32(dr("CustomerID").ToString()),
                .AccNum = dr("AccountNumber").ToString(),
                .Descri = dr("Description").ToString(),
                .CurrBalance = dr("CurrentBalance").ToString(),
                .typOA = dr("TypeOfAccount").ToString(),
                .Frozen = dr("Frozen").ToString()
                }
                accs.Add(acc)
            End While
        End If
    End Using
End Using
Dim js = New JavaScriptSerializer()
Dim strResponse As String = js.Serialize(accs)

<strike>Context.Response.Write(strResponse)</strike>

replace with:

Return strResponse

End Sub

And then the returned object will be {"d": "[{"custID":2,"AccNum":"KODSW00002","Descri":"","CurrBalance":0,"Frozen":false,"typOA":0}]"}, which can be accessed via response.d in your javascript.

$.ajax({
         type: "POST",
         url: "CustomerService.asmx/GetAccounts",
         data: '{"custid":"' + cusID + '"}',
         contentType: "application/json; charset-utf-8",
         dataType: "json",
         success: function (data) {
             alert(data.d); // Should correctly get the response in the d variable.

https://stackoverflow.com/a/20471116/4008833

Upvotes: -2

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131601

JavascriptSerializer is deprecated. It was created long before most de-facto JSON standards, certainly before any actual standards. For example, it doesn't use the de-facto ISO8601 date format.

Microsoft's own documentation says at the very top:

Json.NET should be used serialization and deserialization. Provides serialization and deserialization functionality for AJAX-enabled applications.

Microsoft itself is using Json.NET in ASP.NET MVC Web API.

With Json.NET you can use JsonConvert.Serialize to generate a Json string from a list of objects:

Dim strResponse As String = JsonConvert.Serialize(accs)

Upvotes: 2

Related Questions