views:

240

answers:

4

I'm using jQuery to call an asmx and return some data. I'm making the call like this

function getRequestInfo(event) {
        var id = $('#<%= RequestDaysId.ClientID %>').val();
        var formattedId = "{'id': '115'}";
        $.ajax({
            type: "Post",
            url: "services/VacationServices.asmx/GetVacationInfo",
            data: "{'id': '" + id + "'}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            processdata: true,
            success: function(data) {
                $('#<%=Note.ClientID %>').val(data.Note);
                $('.pendingrequestinfo').show().fadeIn(2000);
            },
            error: function(result, errortype, exceptionobject) {
                $('.failureMessage').fadeIn(2000).fadeOut(2000);
            }
        })
    };

Everything seems to be working fine, I set a break point in my success function and inspect the data object and see this.

"{"Note":"this is a note","dayInfo":[{"ShortDate":"3/4/2010","DayType":"Vacation","HalfDay":""},{"ShortDate":"3/5/2010","DayType":"Vacation","HalfDay":""}]}"

The problem comes when I try to get the values out of the JSON. If I do something like data.Note, I get undefined back.

It's late, It's Saturday and I've been at it all day, I sure would like a push in the right direction when it comes to parsing though my JSON.

EDIT: I'm using Asp.net and JavaScriptSerializer.Serialize() to create the JSON. When I set a break point and inspect the 'data' object it looks to have a property d that contains the string that should be JSON.

ANOTHER EDIT: If I do something like this in my success

$('#<%=Note.ClientID %>').val(data.d.[0]);

I get the { opening curly brace. I guess i'm getting a string instead of JSON, but it seems to go against what the jquery api states about the return value when the datatype is set to JSON.

Thanks guys. Jim

+1  A: 

That's not a valid JSON format. Remove the doublequotes at beginning and end to make it fullworthy JSON.

BalusC
interesting...I'm using the JavaScriptSerializer.Serialize() method to create the json from an object and returning that.
jim
I have no idea what platform you're using, but it look like to be ASP.NET. I'm sorry, I have no answer for that. I would have suggested Google Gson for JSP/Servlet and `json_encode()` for PHP. By the way, aren't those quotes just accidently inserted during writing of the response output or during debugging of the JS?
BalusC
The variable 'data' *is* a data object and not simply a string? Are you sure the JSON string is being deserialised? If it is just a string it might explain why data.Note is giving undefined.
Stephen Curran
The `dataType: "json"` is correctly definied in `$.ajax`, so it should have been deserialized.
BalusC
Right. But I thought it might be worth checking in the debugger just in case.
Stephen Curran
I'm using asp.net for what it's worth and when I get the 'data' back it has a property of d that contains the string that's supposed to be json.
jim
Thats strange. 'data' should be the deserialised json. I don't think it should have a property of 'd'. It might be worth checking the contents of the HTTP response to see exactly what is being returned by the script you are posting to. I created a test using your jquery code and a php script that returned the same json string and it worked fine.
Stephen Curran
this is strange, the api documentation states In jQuery 1.4 the JSON parsing is done in a strict manner, any malformed JSON is rejected and a parsererror is thrown. which I can attest to as I ran into it countless times forming my JSON in the first place
jim
Again, I'd take a look at the HTTP response to see exactly what is being returned by the script handling the AJAX request.
Stephen Curran
+2  A: 

First make sure that the JSON string exists in the "d" variable in the response returned in the success callback. Next, in order to get the JSON object you will need to convert the string into the JSON. You can use the eval function or the JQuery built in function to convert string to JSON. I like the jquery-json plug in to convert string into JSON representation.

Your code will look something like this:

var jsonObject = eval('(' + data.d + ')'); 

Now, you can use jsonObject.Note or any other property.

With jquery-json plugin you can do the following:

var note = $.evalJSON(data.d).Note;
azamsharp
+1 for the work around...this is where I was headed next if I didn't find the answer.
jim
+1  A: 

This one is so silly...sorry guys. When returning data from the asmx there is no need to serialize it into JSON

I have the following class that I'm populating and returing from my web method

public class VacationInfo
    {
        public string Note { get; set; }
        public List<DayInfo> dayInfo { get; set; }
        public VacationInfo(string note, List<DayInfo> dayinfo)
        {
            this.Note = note;
            this.dayInfo = dayinfo;
        }

        public class DayInfo
        {
            public string ShortDate { get; set; }
            public string DayType { get; set; }
            public string HalfDay { get; set; }
            public DayInfo(string shortdate, string daytype, string halfday)
            {
                this.ShortDate = shortdate;
                this.DayType = daytype;
                this.HalfDay = halfday;
            }
        }
    }

as long as your web service is decorated with

     [System.Web.Script.Services.ScriptService]

your object will be serialized and returned as JSON at no charge to you. :)

then I'm able to do this

data.d.Note

in my call back.

Thanks for the help guys.

Credit where credit is due

jim
FYI, See my answer regarding the .d and making it cross version compatible. Just in case that helps you some :) Luck to you.
Mark Schultheiss
thank you...I see what you did there and I plus 1ed you. :) It's my first week with jquery and I'm having a lot of fun with it, it's made client side coding fun.
jim
+1  A: 

Here is how I process. Note the dataFilter: part - this makes it work with either newer or older asp.net stuff.

$.ajax({ 
      type: "POST", 
     contentType: "application/json; charset=utf-8", 
       data: objectSaveData, 
       dataFilter: function(data) 
       { 
           var msg; 
           if (typeof (JSON) !== 'undefined' && 
              typeof (JSON.parse) === 'function') 
               msg = JSON.parse(data); 
           else 
               msg = eval('(' + data + ')'); 
           if (msg.hasOwnProperty('d')) 
                return msg.d; 
           else 
              return msg; 
        }, 
       url: "/mywebservice.asmx/myMethodName",  
       success: function(msg) 
       { 
          //do stuff 
       }, 
        failure: function(msg) 
       { 
          //handlefail 
       } 
  }); 
Mark Schultheiss