Keith Myers
Keith Myers

Reputation: 1369

jQuery ajax json webservice error

If someone could point out what's wrong here I would certainly appreciate it. I can set a breakpoint in the webmethod and it gets hit, but it always errors out.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAX_Test._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>AJAX Test</title>
        <script src="Scripts/jquery-1.7.min.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="form1" runat="server">
            <button id="theButton">Click Here</button>
        </form>
        <script type="text/javascript">
            $(function () {
                $("#theButton").on("click", function () {
                    $.ajax({
                        type: "POST",
                        url: "AjaxWebService.asmx/HelloWorld",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: "{}",
                        success: AjaxSucceeded,
                        error: AjaxFailed
                    });
                });
            });

            function AjaxSucceeded(data, status) {
                alert("success");
            }

            function AjaxFailed(jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        </script>
    </body>
</html>

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

namespace AJAX_Test
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class AjaxWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

Upvotes: 2

Views: 1619

Answers (2)

Marc B
Marc B

Reputation: 360572

You're telling jquery to expect JSON data as a response from the ajax server, but you're sending a bare string as a response. a JSON string would be "Hello World", and the server-side code should be:

return "\"Hello World\"";

Upvotes: 0

Etch
Etch

Reputation: 3054

Here is your problem:

Add this attribute to your service:

[ScriptService]

and add this to your method:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

When you connect to a service from javascript it must have those attributes.

Upvotes: 4

Related Questions