Ajax - Browser Specific Code, just copy and paste below code. This code is for browser specific.
var request = false;
var xmlString;
var microsoft = true;
var updatePage;
function initAjax()
{
try
{
request = new XMLHttpRequest(); // Ajax Class for Mozilla based browsers
microsoft = false;
}
catch (trymicrosoft)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP"); // Ajax Class for IE
}
catch (othermicrosoft)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP"); // Ajax Class for Mozilla based browsers
}
catch (failed)
{
request = false;
}
}
}
This code is must for all AJAX based coding.
Ajax - onreadystatechange Property
Before we even think about sending data to the server, we must first write a function that will be able to receive information. This function will be used to catch the data that is returned by the server.
The XMLHttpRequest object has a special property called onreadystatechange. onreadystatechange stores the function that will process the response from the server. The following code defines an empty function and sets the onreadystatechange property at the same time!
We will be filling this function in throughout the lesson, as you learn more about the XMLHttpRequest object.
I am writing this as a function.
function updatePage()
{
if (request.readyState== 4 || request.readyState=="complete")
{
if(request.status == 200)
{
var obj = document.getElementById('success');
xmlString = request.responseText;
obj.innerHTML=xmlString;
}
else
{
alert("Error :" + request.status );
}
}
}
For GET Method
function addStaff()
{
initAjax();
var obj = document.getElementById('success');
obj.innerHTML="";
var url = "add_data.php";
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
request.open("GET", url+"?bustcache="+new Date().getTime()+"&name="+name+"&password="+password,true);
request.onreadystatechange = updatePage1;
request.send(null);
}
For POST Method
function submitForm()
{
initAjax();
var name = document.getElementById("name").value;
var password= document.getElementById("password").value;
var obj = document.getElementById('success1');
obj.innerHTML="";
var url = "ajax_output.php";
var passData = '&name='+name+'&password='+password;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = updatePage;
request.send(passData);
}
No comments:
Post a Comment