1

I have this function to get me back a list of managers

function getManagers() {
   var jqxhr = $.ajax({
                   type: 'POST',
                   contentType: "application/json; charset=utf-8",
                   url: '/webservice.asmx/GetManagers',
                   dataType: 'json'
               }).success(function(data) {
                   var options = '<option selected="selected" disabled="disabled">Select Manager</option>';
                   for (var i = 0; i < data.length; i++) {
                       options += '<option value="' + data[i].PostRef + '">' + data[i].Description + '</option>';
                   }
                   $('#ReceivingCellManager').html(options);
               }).error(function(data) {
                   $('.ErrorText').html('Manager load failed please refresh page with F5');
                   $("#errormessage").dialog('open');
               }).complete(function() {
           });
} 

as you can see I am using JQuery and want to popoulate a drop down list with the available managers

the method within my service looks like this

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void GetManagers()
    {
        using (var context = new ConcessionModel())
        {             
            var rcm = Business.GetManager();
            var serializer = new JavaScriptSerializer();
            var response = rcm.Count() != 0
                ? serializer.Serialize(rcm)
                : serializer.Serialize(new Error { Code = "500", Message = "Manager Retrieval Failed" });
            this.Context.Response.Clear();
            this.Context.Response.ContentType = "application/json";
            this.Context.Response.Write(response);
        }
    }

When the method is called I recieve a response of 200 OK and the response contains the JSON I want the problem I am having is that the response is not being recognised as JSON.

I HAVE TRIED

  • adding dataType to the ajax call as you can see above
  • removing this.Context.Response.flush from the end of the response, this cured an error I was getting with adjusting headers after they were sent.
  • adding a response format to the method
  • adding a Response.ContentType to the Context These have all failed to get me the required recognition of the JSON. Any help would be much appreciated.

UPDATE: JSON FORMAT

{"Description":"data","Code":"data","reference":"data"}

UPDATE JSON RESPONSE I am seeing something weird in the response my response is as follows

[{"Description":"data","Code":"data","reference":"data"}]{"d":null}

I am not sure what the d null object is

Deviland
  • 3,324
  • 7
  • 32
  • 53
  • why don't you use WCF (with REST) and a JSON response? ... converting everything yourself is really awful! –  Mar 30 '12 at 08:36
  • 2
    Does your data on succes contain the JSON, and could you post a sample dump? :) – Marco Johannesen Mar 30 '12 at 08:37
  • 1
    @MarcoJohannesen thanks for the response, No the success does not fire, the error does. I have just run a small test and the error does not contain the data either. – Deviland Mar 30 '12 at 08:48
  • 1
    Check the response using something like fiddler to see what error you are getting in your code. – Richard Dalton Mar 30 '12 at 08:50
  • @MarcoJohannesen I cannot post the data here as it contains some sensitive items I will however post the format – Deviland Mar 30 '12 at 08:52
  • I have looked through Fiddler at the request and response and Fiddler is able to see and recognise the data returned as JSON – Deviland Mar 30 '12 at 09:04
  • If you use a alert(data) or console.log(data) does it dump the data correctly? – Marco Johannesen Mar 30 '12 at 09:21
  • @MarcoJohannesen If I do this I get an **object** returned, please see my latest edit to see what I have found – Deviland Mar 30 '12 at 09:29

5 Answers5

6

In order to access the json object such as an object of class 'Dog' from the service, the method return type should be 'Dog'. Do not use response.write in services. You can then access the data from the success message using 'data.d'.

Hope this helps!

Kevin Vella
  • 1,869
  • 1
  • 16
  • 18
2

resolved the issue by removing the contentType from the ajax request and adding settings to the web config as described in this post Request format is unrecognized for URL unexpectedly ending in

Thanks for all your help 1 ups all round :)

Community
  • 1
  • 1
Deviland
  • 3,324
  • 7
  • 32
  • 53
1

This worked for me:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    string strResponse = serializer.Serialize("World"); ;

    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.AddHeader("content-length", strResponse.Length.ToString());
    Context.Response.Flush();

    Context.Response.Write(strResponse);


}
Andre Evangelista
  • 3,390
  • 1
  • 21
  • 14
1

Try to parse it as i have shown below , it works for me:

var result = JSON.parse(data, function (key, value) {
                    var type;
                    if (value && typeof value === 'object') {
                        type = value.type;
                        if (typeof type === 'string' && typeof window[type] === 'function') {
                            return new (window[type])(value);
                        }
                    }
                    return value;
                });

And change the data to result:

for (var i = 0; i < result.length; i++) {
                       options += '<option value="' + result[i].PostRef + '">' + result[i].Description + '</option>';
                   }
Dhaval Shukla
  • 1,127
  • 2
  • 10
  • 19
  • @dhavaishukla I dont think I need to parse the data into JSON as this should be the expected returned dataType, if I am wrong here please let me know – Deviland Mar 30 '12 at 09:17
1

In the success function, the return object is 'data'.

In order to access the json data you need to access it via 'data.d'.

I cant help but notice that your web service does return void, maybe that could also be why there is no response??

Kevin Vella
  • 1,869
  • 1
  • 16
  • 18
  • I am accessing the data object as data within the loop, the services return void because they are writing a response not returning a standard object. – Deviland Mar 30 '12 at 09:18
  • instead of writing a response, return the whole object. Then the ajax method will recognize it as json! – Kevin Vella Mar 30 '12 at 12:36