locked
Its gives an error undefined Therefore web service works fine RRS feed

  • Question

  • User2072242043 posted

    Hello,

    I have a web service which works fine and gives output as expected. which is

    {"id":3,"classRoom":"hall","classLimit":100}

    And When I try to call that web service using jquery Ajax its gives output as undefined

    Here is my ajax code:

     //Edit row
                $('#mytable').on('click', '#edit', function () {
                    var id = $(this).attr("value");
    alert(id); //Works fine as expected $.ajax({ url: 'AddUpdateDeleteClassRooms.asmx/SelectClassRoomsById', method: 'post', contentType: 'application/json;charset=utf-8', data: '{roomId:' + JSON.stringify(id) + '}', success: function (result) { alert('Result='+result); }, error:function(err) { alert(console.log(err)); } }); });

    When I trace it through network tab the output is as shown in image

    I don't know why it is adding {"d":null} to webservice response?
    Where is my mistake?
    Please help me

    Thursday, December 15, 2016 12:19 PM

Answers

  • User-1838255255 posted

    Hi Radhesham Khatri,

    According to this error message, as far as I know, may be you use the response.write sentence in web service, if in this way, return string will add this({"d":null});

    1. you could use string type in your method and use return method.

    2. you could use response.d method to accept returned data, r is a object, d is the data of the object. So you need use this method to get data.

      success: function (r) {
                    alert(r.d);
                },

    3. I found a little small flaw:

    (1). you  could use type:"POST" in AJAX.

    (2). JSON.stringify is a method to convert JS Object to JSON Object, as far as I know, it is not necessary in your code.

    I make a sample for a your reference:

    <head runat="server">
        <title></title>
        <style type="text/css">
            body {
                font-family: Arial;
                font-size: 10pt;
            }
    
            table {
                border: 1px solid #ccc;
                border-collapse: collapse;
            }
    
                table th, table td {
                    padding: 5px;
                }
    
                table, table table td {
                    border: 0px solid #ccc;
                }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td>Name:
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Text="" />
                    </td>
                </tr>
                <tr>
                    <td>Age:
                    </td>
                    <td>
                        <asp:TextBox ID="txtAge" runat="server" Text="" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
                    </td>
                </tr>
            </table>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script type="text/javascript">
                $(function () {
                    $("[id*=btnSubmit]").click(function () {
                        var name = $.trim($("[id*=txtName]").val());
                        var age = $.trim($("[id*=txtAge]").val());
                        $.ajax({
                            type: "POST",
                            url: "ServiceCS.asmx/GetDetails",
                            data: "{ name: '" + name + "', age: " + age + "}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (r) {
                                alert(r.d);
                            },
                            error: function (r) {
                                alert(r.responseText);
                            },
                            failure: function (r) {
                                alert(r.responseText);
                            }
                        });
                        return false;
                    });
                });
            </script>
        </form>
    </body>
    
    WebService:
    
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ServiceCS : System.Web.Services.WebService
    {
    
        public ServiceCS()
        {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
    
        [WebMethod]
        public string GetDetails(string name, int age)
        {
            return string.Format("Name: {0}{2}Age: {1}{2}TimeStamp: {3}", name, age, Environment.NewLine, DateTime.Now.ToString());
        }
    }

    Best Regards,

    Eric Du

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 16, 2016 5:57 AM

All replies

  • User475983607 posted

    That's console.log() does not return the error in string.  Use either 

    error:function(err)
    {
    	alert(err);
    }

    Or

    error:function(err)
    {
    	console.log(err);
    }

    The data property does not look correct.  I think you want this.

    data: JSON.stringify({roomId : id }),

    I don't know why it is adding {"d":null} to webservice response?

    That's the way web methods work. They warp the result in a {d: {} }.

    Thursday, December 15, 2016 12:48 PM
  • User2072242043 posted

    Hello mgebhard,
    Thanks for your consideration on my thread.

    Error alert works fine it alert with 

    undefined

    and when i use console.log to write on console it through error as follow

    Object {readyState: 4, responseText: "{"id":1,"classRoom":"Radhy","classLimit":50}{"d":null}", status: 200, statusText: "OK"}

    Even, if I do try as you said

    data: JSON.stringify({roomId : id }),
    

    It still through same error

    {readyState: 4, responseText: "{"id":1,"classRoom":"Radhy","classLimit":50}{"d":null}", status: 200, statusText: "OK"}

    Could you please explain me bit more about 

    {"d":null}

    Why it append d as null therefore my service gives accurate data.

    Thursday, December 15, 2016 1:06 PM
  • User-1838255255 posted

    Hi Radhesham Khatri,

    According to this error message, as far as I know, may be you use the response.write sentence in web service, if in this way, return string will add this({"d":null});

    1. you could use string type in your method and use return method.

    2. you could use response.d method to accept returned data, r is a object, d is the data of the object. So you need use this method to get data.

      success: function (r) {
                    alert(r.d);
                },

    3. I found a little small flaw:

    (1). you  could use type:"POST" in AJAX.

    (2). JSON.stringify is a method to convert JS Object to JSON Object, as far as I know, it is not necessary in your code.

    I make a sample for a your reference:

    <head runat="server">
        <title></title>
        <style type="text/css">
            body {
                font-family: Arial;
                font-size: 10pt;
            }
    
            table {
                border: 1px solid #ccc;
                border-collapse: collapse;
            }
    
                table th, table td {
                    padding: 5px;
                }
    
                table, table table td {
                    border: 0px solid #ccc;
                }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td>Name:
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Text="" />
                    </td>
                </tr>
                <tr>
                    <td>Age:
                    </td>
                    <td>
                        <asp:TextBox ID="txtAge" runat="server" Text="" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
                    </td>
                </tr>
            </table>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script type="text/javascript">
                $(function () {
                    $("[id*=btnSubmit]").click(function () {
                        var name = $.trim($("[id*=txtName]").val());
                        var age = $.trim($("[id*=txtAge]").val());
                        $.ajax({
                            type: "POST",
                            url: "ServiceCS.asmx/GetDetails",
                            data: "{ name: '" + name + "', age: " + age + "}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (r) {
                                alert(r.d);
                            },
                            error: function (r) {
                                alert(r.responseText);
                            },
                            failure: function (r) {
                                alert(r.responseText);
                            }
                        });
                        return false;
                    });
                });
            </script>
        </form>
    </body>
    
    WebService:
    
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ServiceCS : System.Web.Services.WebService
    {
    
        public ServiceCS()
        {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
    
        [WebMethod]
        public string GetDetails(string name, int age)
        {
            return string.Format("Name: {0}{2}Age: {1}{2}TimeStamp: {3}", name, age, Environment.NewLine, DateTime.Now.ToString());
        }
    }

    Best Regards,

    Eric Du

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 16, 2016 5:57 AM
  • User2072242043 posted

    Thanks Eric Du.

    thanks for your help in this regard.
    I was always struggling when I get data from web service in json format.
    A good friend suggested me to use default format of web service which is XML.
    When i return an object in default format I get data as shown below

    <ClassRooms xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
    <id>3</id>
    <classRoom>hall</classRoom>
    <classLimit>100</classLimit>
    </ClassRooms>

    And then In ajax I get this data simply by these code of lines

     //Edit row
                $('#mytable').on('click', '#edit', function () {
                    var id = $(this).attr("value");
                    $.ajax({
                        url: 'AddUpdateDeleteClassRooms.asmx/SelectClassRoomsById',
                        data: { roomId: id },
                        method: 'post',
                        dataType: 'xml',
                        success: function (data) {
                            var xmlData = $(data);//This is xml object
                            var toBeUpdatedRooomName = $('#ClassRoomNameTextBox').val(xmlData.find('classRoom').text());//Received classRoom attribute
                            $('#StudentsLimitTextBox').val(xmlData.find('classLimit').text());//Received classLimit attribute
                        
                        },
                        error: function (err) {
                            alert(console.log(err.d));
                        }
    
                    });

    And hence I'm relax and will not use Json any more when I get back an object.

    Friday, December 16, 2016 7:11 AM