javascriptjquery.netajaxajax-request

Returning an object from Web Service to Ajax Request success callback function


Hello Fellow Developers,

I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.

The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.

 $('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);

 hideValue = function (ev) {
 var $this = $(this);

 $this.data('value', $this.val());
 $('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());

   var data2Send = '{"SSN": ' + $this.val() + ' }';
   $.ajax({
       type: "POST",
       url: "AuthforHire.aspx/EmployeeisRehire",
       data: data2Send,
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (result) {

           var obj = JSON.stringify(result.d);


           if (obj.IsTermed) {
              $('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);       
                 var wndWidth = 900;
                 var wndHeight = 500;
                 var wnd = window.radopen(null, "RadWindowRehire");



             }

         },
         error: function (xhr) {
             alert('Form update failed. ');  //error occurred
         }

     });

Below is a minified version of my webMethod, which works correctly

[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{ 
 TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.

   termedEmp.Name = dr["name"];
   termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
   ......
 }

So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?

Thank you in advance!


Solution

  • The first line in your success callback is:

    var obj = JSON.stringify(result.d);
    

    Which is trying to serialize what ASP.Net will already have serialized for you. Change this to:

    var obj = result.d;
    

    And you will then have access to obj.Name, obj.TermDate and all the other properties by name.