Tuesday 17 January 2012

Wcf webHttpBinding And XMLHttpRequest:-

WcfService:-
namespace WebHttpBindingXmlHttpRequestWcf
{
 [ServiceContract(Namespace = "WebHttpBindingXmlHttpRequestWcf")]
 public interface IService
  {
    [OperationContract]
          string GetData(string input);
   }
}    


namespace WebHttpBindingXmlHttpRequestWcf
{ 
   public class Service : IService
    {  
     public string GetData(string input)
          
{
  
       string output = "You Enter "+ input;
        return output;
          
}
      
}
}

<system.serviceModel>
   <services>
     <service name="WebHttpBindingXmlHttpRequestWcf.Service">
       <endpoint address="webHttpBinding" 
binding="webHttpBinding" 
contract="WebHttpBindingXmlHttpRequestWcf.IService"
behaviorConfiguration="webHttpBindingEndpointBehavior">
       </endpoint>
     </service>
   </services>
    <behaviors>
       <endpointBehaviors>
         <behavior name="webHttpBindingEndpointBehavior">
           <enableWebScript/>
         </behavior>
       </endpointBehaviors>
   </behaviors>
 </system.serviceModel>



JavaScript File:-

//calling wcf service
function callservice(){

//create XMLHttpRequest object
var xmlHttp = new XMLHttpRequest();

//event handler for getting result
xmlHttp.onreadystatechange = function () {
    //check the status of the request(if the status is 4 then all the data is received)
      
if (xmlHttp.readyState == 4) 
       
{
      //here you  get the data.      
         
//alert the result   
          
alert(xmlHttp.responseText);
       
}
};


//error event handler 
xmlHttp.onerror = function (e) {
    //alert the user
    alert('error occurred…');
};


//url of the service
var url = "http://localhost:1094/Service.svc/webHttpBinding/";

//method name
url = url + "GetData";


//here we are passing data to wcf service
var body = '{"input":"1"}';
                                                        
//here we are passing the method type,url and operation type(true for async,false for sync)
xmlHttp.open("POST", url, true);

//adding  header for sending data type(json)
xmlHttp.setRequestHeader("Content-type", "application/json");

//calling service function
xmlHttp.send(body);
} 





Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

No comments:

Post a Comment