Click here to Skip to main content
11,581,397 members (61,419 online)
Click here to Skip to main content

Calling Web Services from HTML Pages using JavaScript

, 29 Jun 2006 CPOL 379.6K 17K 60
Rate this:
Please Sign up or sign in to vote.
This article will help you to call a web service directly from an HTML page
Sample Image - CallWebServiceFromHtml.jpg

Introduction

Hello everyone. In this article, I wanted to show you 'how to call a web service and pass parameters to its methods through HTML pages'. I hope it will be useful.

For this article, we need to create a web service and a web site. Assume that our web service includes these methods...

[WebMethod]
public string HelloWorld() {
    return "Hello World";
}

//This method takes your birth year, month and day, 
//calculates your age and return the year. 
[WebMethod]
public string GetAge(int year, int month, int day) {
    DateTime birthDate = new DateTime(year, month, day);
    long age = new DateTime(DateTime.Now.Ticks - birthDate.Ticks).Year - 1;
    return "You are " + age.ToString() + " years old.";
}

//This method caches the datetime for 4 seconds. 
//also a simple cache implementation. 
private const int CacheTime = 4; // seconds
[WebMethod(CacheDuration = CacheTime,
Description = "As simple as it gets - the ubiquitous Get Date Time.")]
public string GetDateTime() {
    return DateTime.Now.ToString();
}

HTML Pages that Call this Web Service

Your web page directory should include the 'webservice.htc' file. This file adds a behavior to HTML files for calling web services. You can find this file in the *.zip file you will download. I create 3 web pages for this solution.

Note: Please don't forget to change port number for web service access in your HTML pages.

  1. HelloWorld.htm (calls Hello World method):
     <html>
      <head>
       <title>Hello World</title>
        <script language="JavaScript">
         var iCallID;
         function InitializeService(){
          service.useService(http://localhost:1394/MyWebService.asmx?wsdl, 
    	"HelloWorldService");
          service.HelloWorldService.callService("HelloWorld");
         }
         function ShowResult(){
          alert(event.result.value);
         }
        </script>
       </head>
      <body onload="InitializeService()" id="service" 
    	style="behavior:url(webservice.htc)" onresult="ShowResult()"> </body>
     </html>
  2. GetAge.htm (calls GetAge method, takes 3 parameters):
     <html>
      <head>
       <title>UseSwap</title>
        <script language="JavaScript">
         function InitializeService(){
          service.useService(http://localhost:1394/MyWebService.asmx?wsdl, 
    	"GetAgeService");
         }
         var StrYear, StrMonth, StrDay;
         function GetAge(){
          StrYear = document.DemoForm.StringYear.value;
          StrMonth = document.DemoForm.StringMonth.value;
          StrDay = document.DemoForm.StringDay.value;
          service.GetAgeService.callService("GetAge", StrYear, StrMonth, StrDay);
         }
         function ShowResult(){
        alert(event.result.value);
          }
         </script>
        </head>
         <body onload="InitializeService()" id="service" 
    	style="behavior:url(webservice.htc)" onresult="ShowResult()">
          <form name="DemoForm">
           Year : <input type="text" name="StringYear"/>
           Month : <input type="text" name="StringMonth"/>
           Day : <input type="text" name="StringDay"/>
           <button onclick="GetAge()">Get Age</button>
          </form>
         </body>
     </html>
  3. GetDateTime.htm (returns cached value):
     <html>
      <head>
       <meta http-equiv="refresh" content="2" />
       <title>Get Date Time</title>
       <script language="JavaScript">
        var iCallID;
        function InitializeService(){
         service.useService(http://localhost:1394/MyWebService.asmx?wsdl, 
    	"GetDateTimeService");
         service.GetDateTimeService.callService("GetDateTime");
        }
        function ShowResult(){
         alert(event.result.value);
        }
       </script>
      </head>
      <body onload="InitializeService()" id="service" 
    	style="behavior:url(webservice.htc)" onresult="ShowResult()">
      </body>
     </html>

As listed above, there is some JavaScript code written. But it is so easy to understand. First, we add HTML page behavior to access web service, then we make initialization and call the web service method. Soon we get the result by event.result.value. That's all.

You can just copy and paste this code into your HTML pages and it should work. Try the source code if you want. I hope it will be useful. Bye for now.

History

  • 29th June, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gökmen BULUT
Web Developer
Turkey Turkey
Borned in İstanbul/TURKEY....
Loves İstanbul...

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
Lars Bernstorff Hansen2-Oct-14 5:22
memberLars Bernstorff Hansen2-Oct-14 5:22 
QuestionThis will work - Do the changes as mentioned below Pin
Member 828652426-Sep-13 21:22
memberMember 828652426-Sep-13 21:22 
Questionnot working Pin
MM GEHLOT20-Jul-13 2:39
memberMM GEHLOT20-Jul-13 2:39 
QuestionIt doesn't work Pin
AVITALbe21-Apr-13 4:38
memberAVITALbe21-Apr-13 4:38 
AnswerRe: It doesn't work Pin
praveendubey177-Apr-14 5:03
memberpraveendubey177-Apr-14 5:03 
GeneralMy vote of 5 Pin
crcklssp7-Mar-13 19:25
membercrcklssp7-Mar-13 19:25 
QuestionNot working Pin
tej narayan maurya7-Jan-13 18:40
membertej narayan maurya7-Jan-13 18:40 
QuestionI don't know why this doesn't work :( Pin
hipatuwa27-Oct-12 19:45
memberhipatuwa27-Oct-12 19:45 
QuestionCrossBrowser Issue Pin
Member 816917621-Aug-12 1:12
memberMember 816917621-Aug-12 1:12 
GeneralMy vote of 3 Pin
Yogesh Potdar8-Jul-12 7:44
memberYogesh Potdar8-Jul-12 7:44 
QuestionWebservice.htc example works only in IE Pin
Shamims8-Jun-12 7:44
memberShamims8-Jun-12 7:44 
GeneralMessage Automatically Removed Pin
6-Jun-12 1:59
membertrerttyghf6-Jun-12 1:59 
QuestionDataSet and DataTAble Pin
Denisrq22-Mar-12 10:07
memberDenisrq22-Mar-12 10:07 
AnswerRe: DataSet and DataTAble Pin
Yogesh Potdar8-Jul-12 7:48
memberYogesh Potdar8-Jul-12 7:48 
GeneralRe: DataSet and DataTAble Pin
Denisrq9-Jul-12 5:46
memberDenisrq9-Jul-12 5:46 
Questioncorss domain? Pin
JasonJoh15-Mar-12 5:53
memberJasonJoh15-Mar-12 5:53 
GeneralMy vote of 5 Pin
muhammadali7-Mar-12 20:04
membermuhammadali7-Mar-12 20:04 
Newserror Pin
ranadheerk28-Feb-12 22:43
memberranadheerk28-Feb-12 22:43 
QuestionHow come... Pin
pergh23-Mar-11 8:37
memberpergh23-Mar-11 8:37 
GeneralMy vote of 5 Pin
ishmayel14-Nov-10 22:59
memberishmayel14-Nov-10 22:59 
GeneralMy vote of 2 Pin
Norm .net27-Oct-09 21:53
groupNorm .net27-Oct-09 21:53 
You if you formatted this properly it would make good reference article.
GeneralUndefined Pin
PiyushHanda30-Sep-09 21:17
memberPiyushHanda30-Sep-09 21:17 
GeneralMy vote of 2 Pin
rajuxxx16-Apr-09 21:53
memberrajuxxx16-Apr-09 21:53 
GeneralHi everyone.I think my next article will solve your problems. Pin
Gökmen BULUT12-Feb-09 0:21
memberGökmen BULUT12-Feb-09 0:21 
GeneralRe: Hi everyone.I think my next article will solve your problems. Pin
Velmurugan Arjunan6-Apr-09 20:36
memberVelmurugan Arjunan6-Apr-09 20:36 
QuestionHow can i run this in Firefox? Pin
justindhas11-Oct-07 23:21
memberjustindhas11-Oct-07 23:21 
AnswerRe: How can i run this in Firefox? Pin
sebas.naveen15-Nov-07 1:20
membersebas.naveen15-Nov-07 1:20 
AnswerRe: How can i run this in Firefox? Pin
sandy_sam28-Nov-07 19:59
membersandy_sam28-Nov-07 19:59 
GeneralRe: How can i run this in Firefox? Pin
danYYac28-Jan-09 21:52
memberdanYYac28-Jan-09 21:52 
GeneralRe: How can i run this in Firefox? Pin
Talal Sultan11-Feb-09 2:48
memberTalal Sultan11-Feb-09 2:48 
General'event.result.value' is null ot not an object Pin
pargath ranan8-Feb-07 1:23
memberpargath ranan8-Feb-07 1:23 
QuestionHow to pass user name & password ?? Pin
nssidhu6-Nov-06 5:46
membernssidhu6-Nov-06 5:46 
Questionservice? Pin
codePimp12-Sep-06 10:12
membercodePimp12-Sep-06 10:12 
AnswerRe: service? Pin
jayarao28-Oct-06 4:57
memberjayarao28-Oct-06 4:57 
GeneralRe: service? Pin
tim.s.bell14-Jun-07 9:44
membertim.s.bell14-Jun-07 9:44 
GeneralRe: service? Pin
Patrik Lindström30-Jul-08 6:18
memberPatrik Lindström30-Jul-08 6:18 
AnswerRe: service? Pin
danYYac28-Jan-09 21:53
memberdanYYac28-Jan-09 21:53 
Generaluse Atlas Pin
Herre Kuijpers6-Jul-06 4:32
memberHerre Kuijpers6-Jul-06 4:32 
GeneralZip file is empty Pin
Alan Lemming29-Jun-06 3:20
memberAlan Lemming29-Jun-06 3:20 
GeneralRe: Zip file is empty Pin
Gökmen BULUT29-Jun-06 6:49
memberGökmen BULUT29-Jun-06 6:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 29 Jun 2006
Article Copyright 2006 by Gökmen BULUT
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid