ASP.NET - How to call a webservice from normal html page using javascript

Asked By balaji mogadali on 16-Feb-12 12:55 AM
Hi frds

How to call a webservice from javascript from html 
i need code that work from normal html page

pls help 

Sandeep Mittal replied to balaji mogadali on 16-Feb-12 01:06 AM
function getData(CustId) {
  var url = "http://50.0.1.55/WebServicePageName.asmx";
  var req_params;
  req_params = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
  req_params = req_params + "<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/\">";
  req_params = req_params + "  <soap:Body>";
  req_params = req_params + "    <WebServiceFunction xmlns=\"http://tempuri.org/\">";
  req_params = req_params + "    <CustomerId>" + CustId + "</CustomerId>";
  req_params = req_params + "    </WebServiceFunction>";
  req_params = req_params + "  </soap:Body>";
  req_params = req_params + "</soap:Envelope>";
  try {
    ajax_request = new XMLHttpRequest();
  }
  catch (trymicrosoft) {
    try {
      ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (othermicrosoft) {
      try {
        ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (failed) {
        ajax_request = false;
      }
    }
  }
  ajax_request.open("POST", url, true);
  ajax_request.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
  ajax_request.onreadystatechange = receiveXMLInsertData;
  ajax_request.send(req_params);
 }
 
function receiveXMLInsertData() {
  if (ajax_request.readyState == 4) {
 
    if (ajax_request.status == 200) {
    }
  }
  alert('success');
}
Web Star replied to balaji mogadali on 16-Feb-12 01:08 AM
See this is good article to describe how can call websercies in normal html page using javascript
http://www.codeproject.com/Articles/14610/Calling-Web-Services-from-HTML-Pages-using-JavaScr 
Hope this helps you
Somesh Yadav replied to balaji mogadali on 16-Feb-12 01:18 AM

In Aspx section,

Add a ScriptManager tag as follows,

        <asp:ScriptManager ID="ScriptManager1" runat="server">
               
<Services>
                   
<asp:ServiceReference  path="~/sample.asmx"/>
               
</Services>
         
</asp:ScriptManager>

In JavaScript call the web service(sample.asmx) as follows,

<script language="javascript" type="text/javascript">

 
function CalledOnAnyClientClickEvent()
 
{
     
var parameter1="dsfsfs";

     
NameSpace1.WebService1.HelloWorld(parameter1,OnSucess,OnFail);
 
}
   
function OnSuccess(asd)
   
{
      alert
(asd);//result will contain the return parameter from web service
   
}

   
function OnFail(asd)
   
{
      alert
(asd);
   
}
</script>

See the Asmx section (sample.asmx) below,

          using System;
         
using System.Collections.Generic;
         
using System.Linq;
         
using System.Web;
         
using System.Web.Services;

         
using System.Web.Script.Serialization;
         
using System.Web.Script.Services;

         
namespace NameSpace1
         
{
           
/// <summary>
           
/// Summary description for WebService1
           
/// </summary>
           
[WebService(Namespace = "http://tempuri.org/")]
           
[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.
           
[ScriptService]

           
public class WebService1 : System.Web.Services.WebService
           
{

                 
[WebMethod]
                   
public string HelloWorld(string par1)
                   
{
                       
//do your logic here

                       
return "Hello World";
                   
}
           
}
         
}

Hope this helps...

DL M replied to balaji mogadali on 16-Feb-12 01:19 AM
Hi..

you can use below code for call a webservice from javascript to html form

function CreateHintsDivs(result)

   {

       for(var k=0;k

        {        

          var html ="";

html = html + "
"+result[k].Hints +"

"

        }

        var hintdiv = document.getElementById("HindDivID");

        hintdiv.innerHTML = html;

    }

Read more
------------
http://www.a2zdotnet.com/View.aspx?Id=15
Reena Jain replied to balaji mogadali on 16-Feb-12 01:47 AM
Hi,

Create WebService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
 
 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
 
   
 
    [WebMethod]
    public int CheckDuplicate(string User_Name)
    {
       
        string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True";
        string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name";
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand(strQuery, con);            
        cmd.Parameters.Add("User_Name", User_Name);
        con.Open();
        int RetVal= (int)cmd.ExecuteScalar();
        con.Close();
        return RetVal;
        
    }
    
}
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
Add http://www.asp.net/AJAX/Documentation/Live/mref/T_System_Web_UI_ScriptManager.aspx Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the http://www.asp.net/AJAX/Documentation/Live/mref/T_System_Web_UI_ScriptManager.aspx control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.
<asp:ScriptManager runat="server" ID="scriptManager">
        <Services>
            <asp:ServiceReference Path="WebService.asmx" />
        </Services>
    </asp:ScriptManager>

Define the JavaScript code to call the Web Service :
<script language="javascript" type="text/javascript">
 
        // This function calls the Web service method 
        // passing simple type parameters and the 
        // callback function 
        function CallWebMethod() {
            var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value;
            WebService.CheckDuplicate(User_Name, OnSucceeded, OnError);
        }
 
        // This is the callback function invoked if the Web service
        // succeeded
        function OnSucceeded(result) {
            var rsltElement = document.getElementById("lblDuplicate");
            if (result == 1)
                rsltElement.innerHTML = "This User Name is exist";
            else
                rsltElement.innerHTML = "";
 
        }
 
        function OnError(error) {
            // Display the error.
            alert("Service Error: " + error.get_message());
        }
     
    </script>

This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns.

If the Web Service in different Namespace you can refer it before the class name this Main formula may help you : 

NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function);

Parameters: you can pass one or many parameters.

Success callback function :handles returned data from the service .

Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.


Ref: http://weblogs.asp.net/yousefjadallah/archive/2010/03/06/preventing-duplicate-data-with-asp-net-ajax.aspx