Introduction
Very often, there is a need to make server calls from the client without posting the page. Such a scenario occurs in a typical case such as:
A page contains fields namely:
- username
- password
- dropdown list to be populated from the database based on user credentials
Here, when the user enters his name and password, a server call is to be made, and based on his permissions, the values to be shown in the dropdown list should be fetched from the database. This whole activity should happen without posting the page back to the server. In such a scenario, we get stuck and don't have a solution. One of the ways to achieve this is by using the IFrame
control. A sample code snippet is shown below demonstrating how to achieve this.
Using the code
The sample code below shows how to create an IFrame
control to make a call to the server. Subsequently, a callback method is shown which can be called while returning back from the server. The code is commented wherever required.
var IFrameObj;
function callToServer(targetURL)
{
if (!document.createElement)
{
return true;
}
var IFrameDoc;
var URL = targetURL + BuildQueryString(targetURL);
if (!IFrameObj && document.createElement) {
try {
var tempIFrame=document.createElement('iframe');
tempIFrame.setAttribute('id','RSIFrame');
tempIFrame.setAttribute('src','tPCallsForMetaData.aspx');
tempIFrame.style.border='0px';
tempIFrame.style.width='0px';
tempIFrame.style.height='0px';
IFrameObj = document.body.appendChild(tempIFrame);
if (document.frames) {
IFrameObj = document.frames['RSIFrame'];
}
}
catch(exception) {
iframeHTML='<iframe id="RSIFrame" style="';
iframeHTML+='border:0px;';
iframeHTML+='width:0px;';
iframeHTML+='height:0px;';
iframeHTML+='"><\/iframe>';
document.body.innerHTML+=iframeHTML;
IFrameObj = new Object();
IFrameObj.document = new Object();
IFrameObj.document.location = new Object();
IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
IFrameObj.document.location.replace = function(location)
{
this.iframe.src = location;
}
}
}
if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument)
{
setTimeout('callToServer()',10);
return false;
}
if (IFrameObj.contentDocument)
{
IFrameDoc = IFrameObj.contentDocument;
}
else if (IFrameObj.contentWindow)
{
IFrameDoc = IFrameObj.contentWindow.document;
}
else if (IFrameObj.document)
{
IFrameDoc = IFrameObj.document;
}
else
{
return true;
}
IFrameDoc.location.replace(URL);
return false;
}
function handleMetaData(passResult1, ratingList)
{
if (passResult1 == "Unauthorized")
{
alert("Unauthorized access: Please enter " +
"valid userName, Password, Account.");
UserName.focus();
return;
}
else
{
UserName.disabled = true;
Password.disabled = true;
Account.disabled = true;
if (document.getElementById("Rating") != null)
{
Rating.options.length = 0;
PopulateDropDown(ratingList, Rating);
}
}
}