17Feb/100
GET and POST with JavaScript – with XMLHttpRequest
This is an example on how to make a POST call to a WCF service using JavaScript. Notice the XML to send is passed thru in the 'send' method. The XML type must be sent if you are sending XML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var url = 'http://example.com/myservice';
var xml = '<?xml version="1.0" encoding="utf-8" ?><Root xmlns="http://schemas.datacontract.org/2004/07/MyServiceDomain"><Name>John</Name><Language>UK</Langguage></Root>';
function getHTTPObject() {
if (typeof XMLHttpRequest != 'undefined') {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
return false;
}
function useHttpResponse() {
if (http.readyState == 4) {
var textout = http.responseText;
doSomething(textout);
}
}
function doSomething(textout) {
alert(textout);
}
var http = getHTTPObject();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "text/xml");
http.onreadystatechange = useHttpResponse;
http.send(xml);
</script>
</head>
<body>
</body>
</html>
NOTE: You cannot make calls to services or files outside your local domain. If you wish to call a service from another domain (for example a Yahoo or Google service), you must create a proxy page that calls the external service. Your JavaScript will call your proxy page.
Here is an example of a GET call. Notice that the URL and the request parameters are sent thru in the 'open' method. The 'send' method has no arguments.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var url = 'http://example.com/myservice.php?name=John&Language=UK';
function getHTTPObject() {
if (typeof XMLHttpRequest != 'undefined') {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
return false;
}
function useHttpResponse() {
if (http.readyState == 4) {
var textout = http.responseText;
doSomething(textout);
}
}
function doSomething(textout) {
alert(textout);
}
var http = getHTTPObject();
http.open("GET", url, true);
http.onreadystatechange = useHttpResponse;
http.send();
</script>
</head>
<body>
</body>
</html>