Introduction to JQuery.ajax Call in ASP.Net


This article presents an example of how to consume a web service in an ASP.NET application using the jQuery.ajax() method. I have been developing applications running on web browsers for many years and I realize that AJAX and jQuery are getting close to the ultimate dreams of any programmer working on this subject for some time. jQuery is a client-side scripting library, so it is totally independent from the development environment, regardless of whether it is ASP.NET, J2EE, PHP, or any other platform. Visual Studio is readily available to me, so the example is created as an ASP.NET project.

Background

  • What a Web Service is

A “Web Service is the Communication Platform between two different or same platform applications that allows to use their web method.”

By using Web services, your application can publish its function or message to the rest of the world. Web services use XML to code and to decode data and SOAP to transport it (using open protocols). Web Services have two types of uses.

Reusable application-components

There are things applications needed very often. So why make these over and over again?

Web services can offer application-components, like currency conversion, weather reports or even language translation, as services.

Connect existing software

Web services can help to solve the interoperability problem by giving various applications a way to link their data. With Web services you can exchange data between applications and various platforms.

In simple words we can say:

  1. Web services are application components.
  2. Web services communicate using open protocols.
  3. Web services are self-contained and self-describing.
  4. Web services can be discovered using UDDI.
  5. Web services can be used by other applications.
  6. HTTP and XML is the basis for Web services.
  • What a jQuery ajax() Method are

The ajax() method is used to do an AJAX (asynchronous HTTP) request. It provides more control of the data sending and on response data. It allows the handling of errors that occur during a call and the data if the call to the ajax page is successful.

Here is the list of some basic parameters required for jQuery.ajax Method:

  • type: Specifies the type of request (GET or POST).
  • url: Specifies the URL to send the request to. The default is the current page.
  • contentType: The content type used when sending data to the server. The default is “application/x-www-form-urlencoded”.
  • dataType: The data type expected of the server response.
  • data: Specifies data to be sent to the server.
  • success(result,status,xhr): A function to be run when the request succeeds.
  • error(xhr,status,error): A function to run if the request fails.
$.ajax({name:value, name:value, ... })  //The parameters specifies one or more name/value pairs for the AJAX request. 

Code

In the following example we will use ASP.NET to create a simple Web Service that converts the temperature from Fahrenheit to Celsius and vice versa. The structure of the attached Microsoft Visual Studio 2012 solution is as follows:

This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web Services. Here in the TempratureConverter .asmx Web Service I wrote two web methods for a sample application. One is FahrenheitToCelsius() that will convert the temperature from Fahrenheit to Celsius and another one is CelsiusToFahrenheit that will convert the temperature from Celsius to Fahrenheit.

Note : To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line [System.Web.Script.Services.ScriptService].

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Services;  
  
namespace jQuery.AjaxWebServiceCall  
{  
    /// <summary>  
    /// Summary description for TempratureConverter  
    /// </summary>  
    [WebService(Namespace = "http://tempuri.org/")]  
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
    [System.ComponentModel.ToolboxItem(false)]  
    // 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 TempratureConverter : System.Web.Services.WebService  
    {  
  
        [WebMethod]  
        public string FahrenheitToCelsius(string fahrenheit)  
        {  
            return (((Convert.ToDouble(fahrenheit) - 32) / 9) * 5).ToString();  
        }  
  
        [WebMethod]  
        public string CelsiusToFahrenheit(string celsius)  
        {  
            return (((Convert.ToDouble(celsius) * 9) / 5) + 32).ToString();  
        }  
    }  
}  

This document is saved as an .aspx file. In the HTML section of Default.aspx, you can see that we only have a few functional visual components.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQuery.AjaxWebServiceCall._Default" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
    <link rel="stylesheet" type="text/css" href="Styles/mb-ui.css"/>  
    <link rel="stylesheet" type="text/css" href="Styles/jquery-ui.css"/>  
    <script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>  
    <script type="text/javascript" src="Scripts/jquery-ui.js"></script>  
</head>  
<body>  
    <form id="form1" runat="server">  
   <div id="MainDialog" title="Temperature Converter">  
        <table width="100%">  
            <tr>  
                 <td><label>Fahrenheit : </label></td>  
                 <td><asp:TextBox ID="txtFahrenheit1" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
            </tr>  
            <tr>  
                 <td><label>Celsius : </label></td>  
                 <td><asp:TextBox ID="txtCelsius1" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
            </tr>  
            <tr>  
                <td colspan="2"><hr /></td>  
            </tr>  
            <tr>  
                 <td><label>Celsius : </label></td>  
                 <td><asp:TextBox ID="txtCelsius2" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
            </tr>  
            <tr>  
                 <td><label>Fahrenheit : </label></td>  
                 <td><asp:TextBox ID="txtFahrenheit2" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
            </tr>  
        </table>  
    </div>  
    </form>  
</body>  
</html>   

This code shows how to call Web Service methods using a jQuery.ajax call. Here I am calling the Web Method on the TextBox Keyup event so as soon as the user enters data into the TextBox the keyup event is fired and due to the ajax call the result value will be displayed on the page.

<script type="text/javascript">
        $('#' + '<%= txtFahrenheit1.ClientID%>').keyup(function () {  
            if ($('#' + '<%= txtFahrenheit1.ClientID%>').val().length == 0) {  
                $('#' + '<%= txtCelsius1.ClientID%>').val('');  
            }  
            $.ajax({  
                type: "POST",  
                url: "TempratureConverter.asmx/FahrenheitToCelsius",  
                contentType: "application/json; charset=utf-8",  
                dataType: "json",  
                data: JSON.stringify({ 'fahrenheit': $('#' + '<%= txtFahrenheit1.ClientID%>').val() }),  
                success: function (data) {  
                    $('#txtCelsius1').val(data.d);  
                }  
            });  
        });  
        $('#' + '<%= txtCelsius2.ClientID%>').keyup(function () {  
            if ($('#' + '<%= txtCelsius2.ClientID%>').val().length == 0) {  
                $('#' + '<%= txtFahrenheit2.ClientID%>').val('');  
            }  
            $.ajax({  
                type: "POST",  
                url: "TempratureConverter.asmx/CelsiusToFahrenheit",  
                contentType: "application/json; charset=utf-8",  
                dataType: "json",  
                data: JSON.stringify({ 'celsius': $('#' + '<%= txtCelsius2.ClientID%>').val() }),  
                success: function (data) {  
                    $('#txtFahrenheit2').val(data.d);  
                }  
            });  
        });  
    </script>  

You can easily debug jQuery.ajax calls using Firebug in Firefox or Developer Tools in Internet Explorer. You can see the parameters being sent to the Web Service using the ajax call and the response from the Web Service and the time period between the request and the response.

References
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s