Wednesday, March 25, 2009

How to connect to a database server using javaScript?

JavaScript is a scripting language used to enable programmatic access to objects within other applications. It is primarily used in the form of client-side JavaScript for the development of dynamic websites.
Connecting to a database server using javaScript may not be desirable in many instances but
nobody prevents us from doing so.
One of the way of achieving this as below:
Open Notepad.Paste the below code (excluding # of course) in it & save as ".html"

#########################################################

<html>
<head>
<script language="JavaScript">
function testConnection()
{
var dbHost = document.getElementById("txtServerName");
var dbUser = document.getElementById("txtUserName");
var dbPassword = document.getElementById("txtPassword");
var dbProvider = document.getElementById("txtProvider");
var dbDefault = document.getElementById("txtDefaultDB");
var conn_str = "Provider=" + dbProvider.value + ";Data Source=" + dbHost.value + "; User Id=" + dbUser.value + "; password=" + dbPassword.value + "; Initial Catalog=" + dbDefault.value;

var cn = new ActiveXObject("ADODB.Connection");

if(cn)
{
alert(conn_str);

cn.Open(conn_str);

alert("Connected to database...");

cn.close();

return true;
}
return false;
}
function resetFields()
{
var dbHost = document.getElementById("txtServerName");
var dbUser = document.getElementById("txtUserName");
var dbPassword = document.getElementById("txtPassword");
var dbProvider = document.getElementById("txtProvider");
var dbDefault = document.getElementById("txtDefaultDB");

dbHost.value = "";
dbUser.value = "";
dbPassword.value = "";
dbProvider.value = "";
dbDefault.value = "";

return true;
}
</script>
</head>
<body>
<center>
<br><br><br><br><br>
<h1>Connecting to a database using javaScript</h1>
<table>
<tr>
<td>Server Name</td>
<td><input type="text" id="txtServerName"></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" id="txtUserName"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="txtPassword"></td>
</tr>
<tr>
<td>Provider</td>
<td><input type="text" id="txtProvider" value="SQLOLEDB"></td>
</tr>
<tr>
<td>Default DB</td>
<td><input type="text" id="txtDefaultDB" value="TESTDB"></td>
</tr>

<tr>
<td><input type="button" value="Connect" onclick="testConnection();"></td>
<td><input type="button" value="Reset" onclick="resetFields();"></td>
</tr>
</table>
</center>
</body>
</html>

#########################################################