3

I have an ASP.Net web page attempting to retrieve data from an asmx webservice using the jquery .axax method. The ajax method correctly call a success method when the dataType = "text", however I cannot get it to return when using the dataType of "json". Can anyone see what I am missing? I am getting the 'json' example online at http://weblogs.asp.net/jaredroberts/archive/2009/08/28/great-article-on-cascading-dropdown-list-and-jquery.aspx

Client:

function getText() {
    alert("getText");
    $.ajax({ 
        type: "POST", 
        url: "test.asmx/HelloWorld", 
        dataType: "text", 
        success: function(response) { alert("text"); }
    });
}

function getJson() {
    alert("getJson");
    $.ajax({ type: "POST", 
        url: "test.asmx/HelloWorld", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json",
        success: function(response) { alert("json"); }
    });
}

Serverside Webservice Call:

[WebMethod]
public string HelloWorld() {
    return "Hello World";
}
1
  • 1
    You need to json encode that "hello world". Commented Sep 20, 2011 at 20:49

4 Answers 4

2

In the end the source of my issue was the lack of the [ScriptService] attribute on the class decoration. I changed to class declartion to:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class SearchFilters : System.Web.Services.WebService {
    [WebMethod]
    public string HelloWorld() {
        return "";
    }
}

Using Fiddler I discovered the following error message was returned:

Only Web services with a [ScriptService] attribute on the class definition can be called from script

Sign up to request clarification or add additional context in comments.

Comments

1

Your call fails because when you declare the datatype as json, jQuery is expecting JSON as a result, but you return Hello World. Try the code below, instead, to print "Hello World", which is valid JSON.

public string HelloWorld() {
    return """Hello World""";
}

2 Comments

Sorry - I don't know VB at all and assumed it supported escape functionality it doesn't. I have amended my answer.
Actually this is c#, however the above still did not work. Thanks though!
1

Here is what I tried and it worked perfectly:

Client:

<script type="text/javascript">
    $(function () {
        $('#testbutton').click(function () {
            $.ajax({
                type: "POST",
                url: "WebService1.asmx/HelloWorld",
                cache: false,
                contentType: "application/json; charset=utf-8",
                data: "{}",
                dataType: "json",
                success: function (data, status) {
                    var response = $.parseJSON(data.d);
                    alert(response.message);
                    alert(status);
                },
                error: function (xmlRequest) {
                    alert(xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
                }
            });            
        });
    });
</script>

Serverside Webservice Call:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebApplication2
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]    
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {    
        [WebMethod]
        public string HelloWorld()
        {
            return "{ \"message\":\"Hello World\" }";
        }
    }
}

Make sure you have [System.Web.Script.Services.ScriptService] attribute on your webservice class.

NOTE: in the example above the returned JSON is hardcoded, but you can just as easily serialize the objects you want to return as JSON as follows for a hypothetical person object:

Person p = new Person();
p.FirstName = "Bob";
p.LastName = "Smith";
p.Age = 33;
p.Married = true;

Microsoft.Web.Script.Serialization.JavaScriptSerializer jss = new Microsoft.Web.Script.Serialization.JavaScriptSerializer();
string serializedPerson = jss.Serialize(p);

6 Comments

I am afraid this did not work, and as I am at a bank, I am not able to load FF. However I realy want to accomplish what the above article is doing, so why is this not working: public List<Cases> GetCases() { List<Cases> cases = new List<Cases>() { new Cases() { CaseName = "test" } }; return cases.ToList(); }
(sorry for the formatting) In the above example I am calling the 'GetCases' webmethod via 'json' (and 'text') using a jquery call to GetCases. GetCases returns List<OneCase>. However like above, 'text' returns a result, but the 'json' 'success' method never fires. Am I mssing something from the listed MS article?
@davewilliams459 You need to see what the response from your service is. You can use Google Chrome, it has similar tools to Firebug, or install Fiddler for Internet Explorer and profile your ajax requests using that. But first of all, definitely see what is being sent and what is coming back in order to debug this further.
Grrrrr... Chrome, FireFox and Fiddler are restricted here at the bank. I'll have to figure out something. Grrrrr
@davewilliams459 If you are doing web development involving ajax, at least one of those tools is essential to be productive. When i get to work, I'll try creating your solution from scratch and see if it works, i'll send/post a working copy for you.
|
0

Your class must be with attribute : [ScriptService] Then declare method:

  [WebMethod]
    public string GetSomeString()
    {
        return "SomeString";
    }

When you are trying to handle call:

function ShowString() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/YourService.asmx/GetSomeString" ,
            data: "{}",
            dataType: "json",
            success: function (msg) {
                console.debug(msg);
                alert(msg.d);
            }
        });

Will give you proper output what you are expecting "SomeString".

-Raj

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.