|
|
|
|
|
Home
»
AJAX
»
jQuery and Ajax in Microsoft.NET and Oracle AS
|
|
|
Author Rank:
|
|
Total page views :
2140
|
|
Total downloads :
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
Introduction
Ajax and jQuery are emerging technologies gaining an important space in the Web 2.0 world every day. Recent news has confirmed that Microsoft is going to include jQuery in the future ASP.NET release. In this article, I will explain how consume an Ajax-enabled Web service using jQuery through a simple example to see how they fit together. The objective is to have an Ajax-enabled Web service which returns a friendly message (the classic message: "Hello world") which, in turn, is rendered as a HTML document using jQuery code and Microsoft.NET and Oracle AS technologies.
Getting started with the solution inVisual Studio.NET
The first step is to open Visual Studio.NET 2008 and create a Web project for this example, then add an Ajax-enabled Web service to provide the salutation message (see Figure 1).

Figure 1
The service definition is shown in Listing 1.
using System;
using System.Collections; using System.ComponentModel; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using System.Web.Script.Services;
namespace jQueryAndASPNET { /// <summary> /// Summary description for SalutationService /// </summary> [WebService(Namespace = "http://examples.john.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] [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 SalutationService : System.Web.Services.WebService { [WebMethod] public string GetSalutation() { return "Hello world"; } } }
|
Listing 1
In order to add JSON support for the Web service, you should decorate the Web service with the ScriptServiceAttribute found at the assembly System.Web.Script.Services. JSON is the ability to have JavaScript code call a Web service enabling to represent complex data structures in an interchangeable format. The JSON format specification can be found in RFC 4627. This format is an alternative to XML format for the serialization of business entities and its main application is in the Ajax programming model.
After you decorate the Web services using ScriptServiceAttribute, then this service can be called by your any JavaScript program on the client side. Now it's time to start on the jQuery development. You need to download the jQuery library and include it in the project. I've created a "js" directory and add this jquery-1.3.2.js file (see Figure 2).

Figure 2
Now let's create the ASP.NET page to display the result of invocation of the Web service (see Figure 3).

Figure 3
Traditionally, we have included the <asp:ScriptManager> tag in the ASP.NET Web page to reference the Web service (see Listing 2).
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts> <asp:ScriptReference Path="~/js/jquery-1.3.2.js" /> </Scripts> <Services> <asp:ServiceReference Path="~/SalutationService.asmx" /> </Services> </asp:ScriptManager>
|
Listing 2
In this case, we're going to call the Web service directly using jQuery and JSON. In order to invoke the Web service, we're going to add a button inside a panel (a <div> tag) to the page (see Listing 3).
<div> <button id="btnGetMessage">Click to get message</button> </div>
|
Listing 3
And finally, let's write jQuery code to handle the event of clicking the "Click to get message" button, and calling directly the Web service using jQuery and JSON. The mechanism is based on $(document).ready and $.ajax jQuery methods.
The main logic is to use the request type as "POST", set the url of the Web service, specify which data to transfer to the Web service, set the contentType as " application/json; charset=utf-8", set the datatype as "json" and specify a function for success and failure (see Listing 4).
$(document).ready(function() {
$("#btnGetMessage").click(function(event){ $.ajax({ type: "POST", url: "SalutationService.asmx/GetSalutation", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { GetSalutationSucceeded(msg.d); }, error: GetSalutationFailed }); }); });
|
Listing 4
The whole application is shown in Listing 5.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="show_salutationmessage.aspx.cs" Inherits="jQueryAndASPNET.show_ salutationmessage" %>
<!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>Untitled Page</title> <script src ="js/jquery-1.3.2.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $("#btnGetMessage").click(function(event){ $.ajax({ type: "POST", url: "SalutationService.asmx/GetSalutation", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { GetSalutationSucceeded(msg.d); }, error: GetSalutationFailed }); }); }); function GetSalutationSucceeded(msg) { alert('Operation has completed successfully. Message='+msg); } function GetSalutationFailed(msg) { alert('Error message. '+msg.status + ' ' + msg.statusText); } </script> </head> <body> <form id="form1" runat="server"> <div> <button id="btnGetMessage">Click to get message</button> </div> </form> </body> </html>
|
Listing 5
Getting started with the solution in JDeveloper
First of all, let's open JDeveloper and create a new application (see Figure 4).
Figure 4
And an Empty project for the Web components (see Figure 6).

Figure 5
Then, add JSF components to this project. The first component is JSF "Page Flow And Configuration" (the faces-config.xml file) to define the pages and its flow (see Figure 6).

Figure 6
Then drag and drop a JSF Page shape from the JSF Navigation Diagram panel onto the surface of the faces-config.xml file and name it /show_messagesalutation.jsp. Double-click on this shape and define the page.
Now we're going to invoke the Ajax-enabled Web service hosted in the ASP.NET environment defined in the previous section from this page JDeveloper using jQuery and JSON.
In order to use the jQuery library, we need to copy the js directory along with the jquery-1.3.2.js, ui.core.js and ui.draggable.js files to the Web content directory in JDeveloper ([ProjectName]\public_html).
Now let's find out the URL of the Web service (see Figure 7).

Figure 7
Next step is to include the jQuery code in the JSP page inside the <html>/<head> tag inside the <f:view> jsp tag (highlighted in yellow). And include the HTML elements to show the button inside the <h:form> jsp tag (highlighted in yellow). See the resulting JSP, HTML and jQuery code in Listing 6.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page contentType="text/html;charset=windows-1252"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%@ taglib uri="http://xmlns.oracle.com/adf/faces" prefix="af"%> <%@ taglib uri="http://xmlns.oracle.com/adf/faces/html" prefix="afh"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%> <%@ taglib uri="http://xmlns.oracle.com/adf/faces/webcache" prefix="afc"%> <%@ taglib uri="http://xmlns.oracle.com/adf/industrial/faces" prefix="afi"%> <f:view> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/> <title>Create Department</title> <script src="js/jquery-1.3.2.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $("#btnGetMessage").click(function(event){ $.ajax({ type: "POST", url: http://localhost:2837/SalutationService.asmx/GetSalutation, data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { GetSalutationSucceeded(msg.d); }, error: GetSalutationFailed }); }); }); function GetSalutationSucceeded(msg) { alert('Operation has completed successfully. Message='+msg); } function GetSalutationFailed(msg) { alert('Error message. '+msg.status + ' ' + msg.statusText); } </script> </head> <body> <h:form binding="#{backing_show_messagesalutation.form1}" id="form1"> <div> <button id="btnGetMessage">Click to get message</button> </div> </h:form> </body> </html> </f:view> <%-- oracle-jdev-comment:auto-binding-backing-bean-name:backing_show_messagesalutation--%>
|
Listing 6
Now after you run the application and click on the "Click to get message", the remote Web service hosted in ASP.NET environment is invoked and result is displayed using an alert windows (see Figure 8).
 Figure 8
Conclusion
In this article, I've explained how consume an Ajax-enabled Web service using jQuery through a simple example to see how they fit together through an Ajax-enabled Web service which returns a friendly message (the classic message: "Hello world") which, in turn, is rendered as a HTML document using jQuery code and Microsoft.NET and Oracle AS technologies.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
John Charles Olamendy
He’s a senior Integration Solutions Architect and Consultant. His primary area of involvement is in Object-Oriented Analysis and Design, Database design , Enterprise Application Integration, Unified Modeling Language, Design Patterns and Software Development Process. He has knowledge and extensive experience in the development of Enterprise Applications using Microsoft.NET and J2EE technologies and standards. He is proficient with distributed systems programming; and business-process integration and messaging using the principles of the Services Oriented Architecture (SOA) and related technologies such as Microsoft BizTalk Server, Web Services (Windows Communication Foundation, WSE, BEA WebLogic, Oracle AS and Axis) through multiple implementations of loosely-coupled system. He’s a prolific blogger contributing to .NET and J2EE communities and actively writes articles on subjects relating to integration of applications, business intelligence, and enterprise applications development. He holds a Master’s degree in Business Informatics at Otto Von Guericke University, Magdeburg, Germany. He was recently awarded as MVP. He currently works in the telecommunication industry and delivers integration solutions for this industry. He harbors a true passion for the technology.
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|