Saturday, September 12, 2009

Call from Javascript to Server via WCF/Json

Here is a simple example of calling to server from javascript side

1. create a new project name = 'WCFJson'
2. add new html page call HTMLPage.htm.
3. paste code to javascript:

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
var url = "http://localhost/WCFJson/Service.svc/rami/isExist";
var body = '{"name":"'+ "ramigggg" + '"}';
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState == 4){
alert( xmlHttp.responseText);
}
}

4. create new wcf service name 'Service.svc'
5. paste code the interface file


[ServiceContract]
public interface IService{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/isExist")]
bool isExist(string name);
}

6. paste code to service file


public class Service : IService
{
#region IService Members
public bool isExist(string name) {
return true;
}
#endregion
}

7. runproject when html file the the startup page....

good luck,
Rami Heleg