Peyman
Peyman

Reputation: 5

JSON undefined parsererror

Im trying to run a sipmle ASP.NET 2 Webmethod with JSON this is my code :

<head>
<title></title>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $("#btGetDate").click(function () {
            $.ajax({
                type: "POST",
                url: "GetDate.asmx/HelloWorld",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(0);
                },
                error:
               function (XMLHttpRequest, textStatus, errorThrown) {
                   $('div#dvDate').html( errorThrown + textStatus);
               }
            });

        });
    });
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="dvDate"></div><input id="btGetDate" type="button" value="Get Date" />
</div>
</form>
</body>
</html>

And The webservice

namespace AJAX_METHODS
{
    /// <summary>
    /// Summary description for GetDate
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class GetDate : System.Web.Services.WebService
    {

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

        [WebMethod]
        public string GetDateTime()
        {
            return DateTime.Now.ToString();
        }
    }
}

I get a parse error back, no idea why.

Thanks for the answers.

Upvotes: 0

Views: 1057

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You forgot to indicate that this service should return JSON by decorating it with the [ScriptService] attribute:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class GetDate : System.Web.Services.WebService

Upvotes: 3

Skilldrick
Skilldrick

Reputation: 70889

A bare string isn't valid JSON. See json.org.

Upvotes: 1

Related Questions