Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » AJAX » jQuery and Ajax in Microsoft.NET and Oracle AS

jQuery and Ajax in Microsoft.NET and Oracle AS

In this article, I will explain how to consume an Ajax-enabled Web service using jQuery.

Author Rank :
Page Views : 4701
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



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).

1.gif

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).

2.gif

Figure 2

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

3.gif

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).

4.gif 


Figure 4

And an Empty project for the Web components (see Figure 6).

5.gif

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).

6.gif


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).

7.gif


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).

8.gif
 
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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
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.
Looking for C# Consulting?
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
i am using the wcf service but i got error that is following by Koteswararao On October 16, 2010
---------------------------
Message from webpage
---------------------------
Cannot process the message because the content type 'application/json; charset=soap+xml' was not the expected type 'application/soap+xml; charset=utf-8'.
---------------------------
OK   
---------------------------

i got this error when implement your mechanism for my service that is simple function take one string arg and return same thing .
i using following javascript code:

 {$.ajax({
        type: "POST", cache: false,
        url: "http://localhost/TestWeb/Service.svc/DoWork",
        data: { s: "koti" },
        contentType: "application/json; charset=soap+xml",
        dataType: "json",
        success: function(msg) {

            $('#result').text(msg.d);
        },
        error: function(msg) { alert(msg.statusText); }
    })

Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.