Friday, June 12, 2009

Jquery Part 4 - AJAX method call through JQuery

The JQuery tool provides a very good, easy to use AJAX interface. I came across a scenario where this could be applied very well. Assume we have a web service that returns the XML data and we need to display the XML output in the web page when the user clicks a button without refresh. We make AJAX calls through JQuery to the server to invoke the web service as given below.



On the button click we need to load the web service data without a post back.

To do that we need to include the JQuery tool kit scripts in the project folder and set the reference to the scripts.

The above code has many components associated with it. $document.ready will determine whether the HTML is loaded completely and rendered. The next function $('#btn1').click will bind the click event to the function following that. So the scripts within the click function will execute when the user clicks the button btn1.

The next line indicates that we are making an ajax call to the web service url "
jqueryAjax.aspx/GetWebServiceResult". The type parameter indicates the request type GET/POST. The data parameter can be used to pass the input parameter to the server side method. In this example the server side method is GetWebServiceResult. So the method declaration will have a tag [WebMethod] on the method's declaration. This method expects an input parameter of type int and it will pass the parameter recieved from client into the web service. From the client side we will pass the value to this method through data parameter in JQuery.

The contentType and dataType parameter will indicate the type of data transferred between client and server.

When the button is clicked, the client side code will execute and invokes the server side method and pass the input parameter to fetch the result. The server side method in turn will invoke the web service and the result is passed in the object "msg". If the AJAX call is successful, the Success function is invoked. If the AJAX call is failed, the failure function will be invoked.

The BuildHTML method will parse the web service results and display in the HTML.

So it is EASY :), No More UpdatePanel, ScriptManager!!!

No comments: