Introduction to JQuery.ajax Call in ASP.Net

Introduction

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. 
  1. $.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].
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6.   
  7. namespace jQuery.AjaxWebServiceCall  
  8. {  
  9.     /// <summary>  
  10.     /// Summary description for TempratureConverter  
  11.     /// </summary>  
  12.     [WebService(Namespace = "http://tempuri.org/")]  
  13.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  14.     [System.ComponentModel.ToolboxItem(false)]  
  15.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  16.     [System.Web.Script.Services.ScriptService]  
  17.     public class TempratureConverter : System.Web.Services.WebService  
  18.     {  
  19.   
  20.         [WebMethod]  
  21.         public string FahrenheitToCelsius(string fahrenheit)  
  22.         {  
  23.             return (((Convert.ToDouble(fahrenheit) - 32) / 9) * 5).ToString();  
  24.         }  
  25.   
  26.         [WebMethod]  
  27.         public string CelsiusToFahrenheit(string celsius)  
  28.         {  
  29.             return (((Convert.ToDouble(celsius) * 9) / 5) + 32).ToString();  
  30.         }  
  31.     }  

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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQuery.AjaxWebServiceCall._Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <link rel="stylesheet" type="text/css" href="Styles/mb-ui.css"/>  
  9.     <link rel="stylesheet" type="text/css" href="Styles/jquery-ui.css"/>  
  10.     <script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>  
  11.     <script type="text/javascript" src="Scripts/jquery-ui.js"></script>  
  12. </head>  
  13. <body>  
  14.     <form id="form1" runat="server">  
  15.    <div id="MainDialog" title="Temperature Converter">  
  16.         <table width="100%">  
  17.             <tr>  
  18.                  <td><label>Fahrenheit : </label></td>  
  19.                  <td><asp:TextBox ID="txtFahrenheit1" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
  20.             </tr>  
  21.             <tr>  
  22.                  <td><label>Celsius : </label></td>  
  23.                  <td><asp:TextBox ID="txtCelsius1" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td colspan="2"><hr /></td>  
  27.             </tr>  
  28.             <tr>  
  29.                  <td><label>Celsius : </label></td>  
  30.                  <td><asp:TextBox ID="txtCelsius2" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
  31.             </tr>  
  32.             <tr>  
  33.                  <td><label>Fahrenheit : </label></td>  
  34.                  <td><asp:TextBox ID="txtFahrenheit2" runat="server" CssClass="text ui-widget-content ui-corner-all" title="Enter Customer Full Name"></asp:TextBox></td>  
  35.             </tr>  
  36.         </table>  
  37.     </div>  
  38.     </form>  
  39. </body>  
  40. </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.
  1. <script type="text/javascript">
  2.         $('#' + '<%= txtFahrenheit1.ClientID%>').keyup(function () {  
  3.             if ($('#' + '<%= txtFahrenheit1.ClientID%>').val().length == 0) {  
  4.                 $('#' + '<%= txtCelsius1.ClientID%>').val('');  
  5.             }  
  6.             $.ajax({  
  7.                 type: "POST",  
  8.                 url: "TempratureConverter.asmx/FahrenheitToCelsius",  
  9.                 contentType: "application/json; charset=utf-8",  
  10.                 dataType: "json",  
  11.                 data: JSON.stringify({ 'fahrenheit': $('#' + '<%= txtFahrenheit1.ClientID%>').val() }),  
  12.                 success: function (data) {  
  13.                     $('#txtCelsius1').val(data.d);  
  14.                 }  
  15.             });  
  16.         });  
  17.         $('#' + '<%= txtCelsius2.ClientID%>').keyup(function () {  
  18.             if ($('#' + '<%= txtCelsius2.ClientID%>').val().length == 0) {  
  19.                 $('#' + '<%= txtFahrenheit2.ClientID%>').val('');  
  20.             }  
  21.             $.ajax({  
  22.                 type: "POST",  
  23.                 url: "TempratureConverter.asmx/CelsiusToFahrenheit",  
  24.                 contentType: "application/json; charset=utf-8",  
  25.                 dataType: "json",  
  26.                 data: JSON.stringify({ 'celsius': $('#' + '<%= txtCelsius2.ClientID%>').val() }),  
  27.                 success: function (data) {  
  28.                     $('#txtFahrenheit2').val(data.d);  
  29.                 }  
  30.             });  
  31.         });  
  32.     </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

Up Next
    Ebook Download
    View all
    Learn
    View all