Monday, December 7, 2009

jQuery web service interaction

To interact with the web service on the client, do the following.

1. Insert the following into a script tag;
$(document).ready(function() {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "wsTestAjax.asmx/HelloWorld",
        data: "{}",
        datatype: "json",
        success: function(msg) {
            var message = eval('(' + msg + ')');
            $(".lblTestAjax").text(message.d);
         }
     });
});

2. Have a literal tag as such within the form;
asp:Label ID="lblTestAjax" runat="server" CssClass="lblTestAjax"

3. Create a web service. In this particular case, I've called it wsTestAjax.asmx and within it, I had the basic function of "Hello World". Code as below:-
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
//This was the 1 line that I was missing, please don't forget to include the next
//line, if not you'll spend the whole day wondering what happened.
[System.Web.Script.Services.ScriptService]
public class wsTestAjax : System.Web.Services.WebService
{
    [WebMethod(EnableSession=true)]
    public string HelloWorld()
    {
        return "Hello World";
    }
}