ASP.NET calling a web service from javascript

Calling a web service from javascript should be a very easy task.
Especially if you are using prototype or jquery in your project.

The other day I spent to much time trying to call a WebService using Prototype js library so I decided to post the code here in case anyone else encounter the same problem.
Server side code:
            [WebService]
            [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
            [System.Web.Script.Services.ScriptService]
            public class WebService : System.Web.Services.WebService
            {
                [WebMethod]
                public string HelloWorld(string testParam)
                {
                    return testParam;
                }
            }
Prototype syntax:
            new Ajax.Request('WebServices/WebService.asmx/HelloWorld',
                {
                postBody: "{testParam:'hello'}",
                method: 'post',
                contentType: 'application/json; charset=utf-8',
                onSuccess: function(transport) {
                    alert(transport.responseText);
                    },
                onFailure: function(transport) {
                    alert(transport.responseText);
                    }
            });
JQuery syntax:
            $.ajax({
                    type: "POST",
                    url: "WebServices/WebService.asmx/HelloWorld",
                    data: "{testParam:'hello'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(result){
                        alert(result.d);
                    }
                });
That’s it.
Hope it help someone out
there.
Happy coding!
Netanel
Advertisements