Wednesday, May 12, 2010

AJAX call to ASMX usng JQuery with error handling

Here's the javascript

        function DoAjaxTest(str) {
            $.ajax({
                type: "POST",
                url: "Service1.asmx/TestMethod",
                data: "{'parameter1': '" + str +"'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                   alert(msg.d);
                },
                error: function (xhr, textStatus, errorThrown) {
                    //debugger;

                    var errObj={Message:'',ExceptionType:'',StackTrace:''};
                    //debugger;
                    if (xhr.status===500) {
                        //a thrown exception will have status 500.  the properties of Message,ExceptionType, StackTrace 
                        errObj = eval('(' + xhr.responseText + ')');
                    }
                    alert(
                        "Status: " + textStatus +
                        "; textStatus: " + textStatus +
                        "; reror Thrown: " + errorThrown +
                        "; status statusText: " + xhr.status + " " + xhr.statusText +
                        "; Error Message: " + errObj.Message +
                        "; 
stack trace:
" + errObj.StackTrace.replace(/\n/g, "
\n") + "
" + //"; xhr.responseText: " + xhr.responseText + "
"); } }); }; $(document).ready(function () { DoAjaxTest('hello world'); });
Here's the content of the Service1.asmx file:
<%@ WebService Language="C#" Class="testService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class testService  : System.Web.Services.WebService {

    [WebMethod]
    public string TestMethod(string parameter1)
    {
        
        return (DateTime.Now.ToLongTimeString() + ": " + parameter1);
    }
}

No comments: