• A2ZMenu.Com
Loading
  • Home
  • Blogs
    • AJAX
    • ASP.NET
    • BI
    • CSharp
    • JavaScript
    • LINQ
    • Miscellaneous
    • SQL
    • SharePoint
    • Silverlight
    • WCF
  • Tutorials
    • HTML5
    • ASP.NET 4.0
    • CSharp
    • SharePoint
    • SQL Function
  • Online Exam
    • ASP.NET
    • LINQ
    • Silverlight
    • SQL
    • JavaScript
    • SharePoint
  • Forum
  • Utility
  • Fun @ Work
    • Appraisal
    • Funny Images
    • Funny Puzzle
    • Miscellaneous
    • Motivating Stories
  • Wiki
  • Contact Us
  • AJAX
  • ASP.NET
  • BI
  • CSharp
  • JavaScript
  • LINQ
  • Miscellaneous
  • SQL
  • SharePoint
  • Silverlight
  • WCF

Test Your Skill

Show/Hide
 Q. I have a web application where I am trying to make a Ajax call using XMLHttpRequest Object. But some times its not working. Seems like its a browser issue. Can you figure out for which browser its not working?
View all questions...
How to call webservice using Ajax or JavaScript
Tweet
mail-image


We can not imaging web space without Ajax (Asynchronous JavaScript and XML) and JavaScript. It reduces page load time and hence a good user experience. Today I will show you a sample code on,"How to call webservice using Ajax or JavaScript". (Download Sample Code)

Steps to call webservice using Ajax or JavaScript:

Step 1: Create XMLHttpRequest object. Given below method returns proper XMLHttpRequest object depending upon browser:

function CreateXMLHttpRequest() {
        if (typeof XMLHttpRequest != "undefined"){
            //All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) uses XMLHttpRequest object
            return new XMLHttpRequest();
     }
        else if (typeof ActiveXObject != "undefined") {
            // Internet Explorer (IE5 and IE6) uses an ActiveX object
            return new ActiveXObject("Microsoft.XMLHTTP");
     }
        else {
            throw new Error("XMLHttpRequestnot supported");
     }
    }

Step 2: Call open method and pass proper parameter as per the requirement
            
           var
objXMLHttpRequest = CreateXMLHttpRequest(); //Create XMLHttpRequest object 
           objXMLHttpRequest.open("POST", <serviceUrl>, false);

Open method accept three parameters, They are mentioned below:
  1. method - Type of request, it can be GET or POST.
  2. serviceUrl - Url of the webservice or page URL.
  3. isAsync - It will be either 'true' or 'false'. Pass true to make asynchronus webservice call.

// Add mentioned below code if your application calls webservice Asynchronously.

objXMLHttpRequest.onreadystatechange = function (){   

       if (objXMLHttpRequest.readyState ==4 && objXMLHttpRequest.status == 200){

             result = objXMLHttpRequest.responseXML;

       }

}

Step 3: Use "setRequestHeader" method to set header of the Http request. For example suppose we have to pass XML data to call webservice. Use mentioned below code:


        objXMLHttpRequest.setRequestHeader("Content-Type","text/xml; charset=utf-8");
          Note: Suppose you do not have to pass any thing in send method then no need set content-type.

Step 4: Finally we have to prepare packet and call send method. Be careful while creating packet because you make small mistake that can waste a lots of time in debugging.
var packet = '<?xml version="1.0" encoding="utf-8" ?>

    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body>

   <WebMethodName xmlns="<Webservice Namespace>">

  <ParameterName>value</ParameterName>

  <ParameterName>value</ParameterName >

  <ParameterName>value</ParameterName>

  </WebMethodName>

     </soap:Body>  </soap:Envelope>';

We need to replace highlighted text with the proper value in the above packet before sending the xml http request. Purpose highlighted text are mentioned below:
  1. WebMethodName - Webmethod name and method name is case sensitive. 
  2. <Webservice Namespace> - Namespace of webservice "http://SampleWebservice.com/"      
    e.g:[WebService(Namespace = "http://SampleWebservice.com/")]
  3. ParameterName - Parameter Name of webmethod and its value
        objXMLHttpRequest.send(packet);
        // Add mentioned below code if your application calls webservice synchronously.
        result = objXMLHttpRequest.responseXML;
        
Now we know how to call webservice using Ajax or JavaScript. Mentioned below sample code of a simple webservice and web-method call using Ajax.

Sample webservice code:

    /// <summary>

    /// Summary description for SampelWebservice

    /// </summary>

    [WebService(Namespace= "http://SampleWebservice.com/")]

    [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 SampelWebservice: System.Web.Services.WebService

    {

        [WebMethod]

        public string HelloWorld(string text)

        {

            return text;

        }

    }

Sample Code for webservice call:

var objXMLHttpRequest = CreateXMLHttpRequest();

objXMLHttpRequest.open("POST", "http://localhost/SampleWebservice.asmx", true);

objXMLHttpRequest.setRequestHeader("SOAPAction","http://SampleWebservice.com/HelloWorld");

var packet = '<?xml version="1.0"encoding="utf-8" ?>

      <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

  <soap:Body>

   <HelloWorld xmlns="http://SampleWebservice.com/">

  <text> Asynchronous webservice call using Ajax</text>

  </WebMethodName>

     </soap:Body>  

     </soap:Envelope>';

 

objXMLHttpRequest.onreadystatechange = function(){

       if (objXMLHttpRequest.readyState == 4 && objXMLHttpRequest.status == 200) {

            result= objXMLHttpRequest.resposeXML;

        }

}

objXMLHttpRequest.send(packet);

I hope, it will help you understand use of Ajax.



Add Comment

Comment
Name
 (Required)
E-mail (Privacy assured)
 (Required)

Poll of the Day

  Who is best CEO so far?
 
 
 

Related Contents

Online Test Papers

  • ASP.NET
  • JavaScript
  • LINQ
  • SharePoint
  • Silverlight
  • SQL

Related Tutorials

  • HTML 5 Tutorial
  • SharePoint Best Practice
  • ASP.NET 4.0 Tutorials

Connect with Facebook

Top Blogs

  • SharePoint 2010 Model Dialog
  • Validation of viewstate MAC failed. If this application is hosted...
  • Silverlight: ListBox with CheckBox
  • Creating a Windows Service in C#
  • Using InstallUtil to install/uninstall service
  • How to call webservice using Ajax or JavaScript
  • LINQ to SQL Best Practice
  • The contract name could not be found in the list of contracts implemented by the service
  • Calling JavaScript function from C#
Blogs
  • AJAX
  • ASP.NET
  • BI
  • CSharp
  • HTML
  • JavaScript
  • LINQ
  • SQL Server
  • SharePoint
  • Silverlight
Tutorials
  • HTML5
  • ASP.NET 4.0
  • CSharp
  • SharePoint
  • SQL Server
Online Examinations
  • ASP.NET
  • LINQ
  • SQL Server
  • JavaScript
  • SharePoint
Online Utilities
  • Age Calculator
  • Happy Birthday Wisher
  • Independence Day Wisher
  • URL Encoder Decoder
  •  
Fun @ Work
  • Appraisal
  • Funny Images
  • Funny Puzzle
  • Miscellaneous
  • Motivating Stories
A2ZMenu © 2012 Home | Contact Us | Privacy Policy | Connect with Facebook | Follow us on Twitter