I am a newbie to ASP.NET and Ajax. I am trying to implement a sample application that updates web form without Postback. On click, my application sends request to its server using XMLHttpRequestModule and shows the data received through an alert window.
I think the problem might be that default.aspx.cs page is not giving the httpRequest.responseText to its webform.
cf. sendRequest method is in XMLHttpRequestModule to check the compatibility with browsers and send a request using the specified parameters and methods.
Any help is much appreciated.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="XMLHttpRuquestModule.htm"></script>
<script type="text/javascript">
function helloToServer() {
var params = "name=" + encodeURIComponent(document.form.name.value);
sendRequest("Default.aspx", params, helloFromServer, "POST");
}
function helloFromServer() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert("Response: " + httpRequest.responseText);
}
}
}
</script>
</head>
<body>
<form name ="form" runat="server">
<input type="text" name="name" />
<input type="button" value="enter" onclick="helloToServer()" />
</form>
</body>
</html>
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String name = Request["name"];
Response.Write(name);
return;
}
}
XMLHttpRequestModule
<head>
<title></title>
<script type="text/javascript">
var httpRequest = null;
function getXMLHttpRequest() {
if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1) {
return null;
}
}
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return null;
}
}
function sendRequest(url, params, callback, method) {
httpRequest = getXMLHttpRequest();
var httpMethod = method ? method : 'GET';
if (httpMethod != 'GET' && httpMethod != 'POST') {
httpMethod = 'GET';
}
var httpParams = (params == null || params == '') ? null : params;
var httpUrl = url;
if (httpMethod == 'GET' && httpParams != null) {
httpUrl = httpUrl + "?" + httpParams;
}
httpRequest.open(httpMethod, httpUrl, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = callback;
httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}
</script>
</head>