Using Ajax we can communicate to server side ASP script without reloading the page. The basic front end of Ajax script is same but the server side script varies. Server side script can be PHP, ASP, Java or any other code. Here we will learn how to integrate Ajax code with ASP files.
You can learn the basic HTTPSML object used for Ajax here
The best use of Ajax is to integrate it with Database handling by ASP. Like this we can crate work on MSSQL tables and develop scripts like login forms, signup scripts, classified scripts etc.
Connecting to Server side ASP script in Ajax
Here we will use one simple form with one submit button. On clicking of the submit button we will trigger the ajaxFunction and submit data to our server side ASP script. There is nothing much in our ASP page, it will only return a message 'Hello World' which we will display in out html page. So let us start with the easy part the post.asp page.
<%
Response.Write "Hello World"
%>
The message "Hello World" will be displayed by the browser at our html page.
As we will be using XMLHttp Request object in all our scripts, you can read more on XMLHttp Request object here.
The HTML page will have Ajax function inside the head tag and within the <script> tag. It will have our form inside its <body > tag. We will start with our Ajax function first. Here it is .
<script type="text/javascript">
function ajaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("txtReturn").innerHTML=httpxml.responseText;
myForm.reset();
}
}
function getFormData(myForm) {
var myParameters = new Array();
for (var i=0 ; i < myForm.elements.length; i++) {
var sParam = encodeURIComponent(myForm.elements[i].name);
sParam += "=";
sParam += encodeURIComponent(myForm.elements[i].value);
myParameters.push(sParam);
}
return myParameters.join("&");
}
var url="post.asp";
var myForm = document.forms[0];
var parameters=getFormData(myForm);
httpxml.onreadystatechange=stateChanged;
httpxml.open("POST", url, true)
httpxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
httpxml.send(parameters)
}
</script>
As you have seen in above code the first part is to establish the XMLHttp request object. Then we will use the function getFormData to collect the form inside values. Here we don't have much thing but we can add different components like textbox , checkbox etc to the form.