Monday, 17 November 2008

RYO AJAX script ...

Because I haven't posted anything for a litle while - I thought I'd dig out some old code and blog it in the name of consistency ...

So here's how to roll your own AJAX - to - .NET XML web-service call:

----------------------------------------------------------------------------
-- YOUR SAMPLE JAVASCRIPT FUNCTIONS --
----------------------------------------------------------------------------
// Get the XMLHttpRequest object
function getXmlHttpRequest()
{
if (window.XMLHttpRequest)
{
    xmlHttpRequest = new XMLHttpRequest();
}
else if (typeof ActiveXObject != "undefined")
{
    xmlHttpRequest = new ActiveXObject(" Microsoft.XMLHTTP");
}
return xmlHttpRequest;
}

// Send the text to server
function sendSelectedText()
{
var xmlHttpRequest = getXmlHttpRequest();
if (xmlHttpRequest != null)
{
    try
    {
 // send data to server
 var url = "http://" + location.hostname + "/AJAXSample/WebService.asmx/GetData?strParam=" + document.getElementById(txtBlah).value;
 xmlHttpRequest.open("GET", url, false);
 xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 xmlHttpRequest.send(null);

 // show returned result
 alert(xmlHttpRequest.responseXML.getElementsByTagName("string")[0].firstChild.data);
    }
    catch(e)
    {
 alert(e.message); 
    }
}
}

...

<input type="button" id="btnBlah" onclick="sendSelectedText()"></input>
<input type="text" id="txtBlah"></input>

------------------------------------------------------------------------------
-- YOUR SAMPLE WEB SERVICE WEBMETHOD --
------------------------------------------------------------------------------
[WebMethod]
public string GetData(string strParam)
{
// your data access code
return "blah blah your data here";
}

------------------------------------------------------------------
-- YOUR SAMPLE WEB.CONFIG FILE --
------------------------------------------------------------------
<system.web>
...
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>

------------------------------------------------------------------

... use it if you dare!!


No comments:

Post a Comment