JavaScript – Working with Database
After reading this coding, you will know the following facts.
- How to connect the database in JavaScript
- How to use the ADODB.Recordset in JavaScript
As I already put the details comments in coding, I hope you will find it useful.
You can download the sourcecode and MSAccess database from this link.
http://michaelsync.net/demo/JavaScriptDatabaseSrc.zip
****
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
<!–
var adOpenDynamic = 2;
var adLockOptimistic = 3;
/* Path of database.
If you put the database "Inventory.mdb" in different location,
you need to specify the correct path to this variable.
But When you are running the webpage from Browsers only,
you should use this keyword "window.location.pathname" for getting
the current location. But If you are using FrontPage,
you hav to specity the static path.
*/
var strDbPath = "C:\\JavaScript Database\\Inventory.mdb";
/*
Here is the ConnectionString for Microsoft Access.
If you wanna use SQL or other databases, you hav
to change the connection string..
eg: SQL => var conn_str = "Provider=sqloledb; Data Source=itdev;" +
"Initial Catalog=pubs; User ID=sa;Password=yourpassword";
*/
var conn_str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDbPath;
function getAdoDb(strAdoType){
if (window.ActiveXObject){
return new ActiveXObject(strAdoType);
}
else{
return new ActiveXObject(strAdoType);
}
}
function showReports(){
try{
var strHtml ="";
strHtml += "<table cellpadding=0 cellspacing=0 border=1 width=500px align=center>";
strHtml += "<tr ><td align=center colspan=4><b>Stock List</b></td></tr>";
//Database Connection
var conn = getAdoDb("ADODB.Connection");
conn.open(conn_str, "", "");
//Recordset
var rs = getAdoDb("ADODB.Recordset");
strQuery = "SELECT StockID,StockName,ReOrderLevel,IsActive FROM Stocks";
rs.open(strQuery, conn, adOpenDynamic, adLockOptimistic);
if(!rs.bof){
rs.MoveFirst();
while(!rs.eof) {
strHtml += "<tr>";
strHtml += " <td width=\"10px\">" + rs.fields(0).value + "</td>";
strHtml += " <td width=\"50px\">" + rs.fields(1).value + "</td>";
strHtml += " <td width=\"10px\">" + rs.fields(2).value + "</td>";
strHtml += " <td width=\"5px\">" + rs.fields(3).value + "</td>";
strHtml += "</tr>";
rs.MoveNext();
}
}
else{
//No Records.
strHtml += "<tr colspan=4><td align=center><font color=red>No Records.</font></td></tr>";
}
conn.close();
strHtml += "</table>";
document.write(strHtml);
}catch(ex){
alert(ex.message);
}
}
//–>
</script>
<title>Stock List</title>
</head>
<!–<body onload="show_menu()">
<div id="main" />–>
<body>
<script language="JavaScript">
showReports();
</script>
</body>
</html>

sorry for late reply and i was too busy during these day.
Please check it this file. [download]
I also made changes your database design..
hope, it would help u.
Hi Mike,
I saw the modifications you had made to the database but the problem is i use sql server and i the mdb is just a working model. I cannot make the kind of changes you made to the mdb file on the sql database for technical reasons. i tried integrating the your code with the file i was working and it dint work it was giving me an error “Data type mistatch” i beieve the reason its working on the mdb is because of the modifications you made at the design level. I understand that you are a very busy person and i am sorry to have kept querying you like this all the time. please tell me if there is a way to get the output the way you already did except without changing anything at the database level.
I hope that you can help me out on this. and i am desperately looking forward to your help on this.
Best Regards
John
just wanted to know how to write a if condidtion to check a value from the database . i.e. if the value is same then display all vaues in the same row if they are different then display them in different rows.
for example in my database table i have 2 fields row and value.
displayed as below.
row Value
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
c 9
c 10
c 11
so now i am trying to check if the value belongs to the same row display in all in one row of a table else display them in a seperate row of the same table.
the output should look like this
a = 1234
b = 5678
c = 91011
is this possible.
Spike
Hi Mike,
I dint see your reply but just wanted to know if you have any suggestion.
Thanks
Spike
Yeah.
It’s not about Javascript. It’s about T-SQL Query String.
Suppose:
Note: the following code is just a concept.. not correct code syntax.
Table Name : Table1
Fields : RowID, RowValue
rs1.GetData (“SELECT RowId FROM Table1 GROUP BY RowID”);
while(rs1.eof){
rs2.GetData(“SELECT RowValue FROM Table1 WHERE RowID=’” + rs1[0] + “‘”);
string str = rs[0] + ” = ” ;
while(rs2.eof){
str += rs2[0];
}
console.log(str); // Here the result wil be logged. eg: a = 1234
rs2.close();
}
rs1.close();
below is my code i tried the group by function but dint quite work can you point out where i am going wrong from the code below
var strHtml =”";
strHtml += “”;
strHtml += “appid“;
var conn = getAdoDb(“ADODB.Connection”);
conn.open(conn_str, “”, “”);
var rs = new ActiveXObject(“ADODB.Recordset”);
strQuery = “SELECT rowvalue FROM table WHERE app_id=’00210′”;
rs.open(strQuery, conn, adOpenDynamic, adLockOptimistic);
strHtml += “”;
if(!rs.bof){
rs.MoveFirst();
while(!rs.eof) {
strHtml += “”+ rs.fields(0).value +”";
rs.MoveNext();
}
}
else{
//No Records.
strHtml += “”;
strHtml += “no data”;
strHtml += “”
}
strHtml += “”;
conn.close();
strHtml += “”;
i am trying to get values that belong to the same row to come in diff td’s of the same row and if the row id is different they should come ina a diff row .
Thanks in advance
Spike
var strHtml =””;
strHtml += “”;
var conn = getAdoDb(”ADODB.Connection”);
conn.open(conn_str, “”, “”);
var rs = new ActiveXObject(”ADODB.Recordset”);
var rs2 = new ActiveXObject(”ADODB.Recordset”); // Declaring another recordset
//If you wanna get all id then you shouldnot use the specific id.
strQuery = “SELECT RowId FROM Table1 GROUP BY RowID”;
rs.open(strQuery, conn, adOpenDynamic, adLockOptimistic);
if(!rs.bof){
rs.MoveFirst();
while(!rs.eof) {
//This is recordset 2
rs2.open(”SELECT RowValue FROM Table1 WHERE RowID=’” + rs.fields(0).value + “‘”, conn, adOpenDynamic, adLockOptimistic);
strHtml += “”+ rs.fields(0).value +””; //result strHtml = “a”
strHtml += “ = “; //result strHtml = “a = ”
if(!rs2.bof){
rs2.MoveFirst();
while(!rs2.eof) {
strHtml += “”+ rs2.fields(0).value +””; //result strHtml = “a = 1234″
rs2.MoveNext();
}
}
rs2.close();
rs.MoveNext();
}
}
else{
//No Records.
strHtml += “”;
strHtml += “no data”;
strHtml += “”
}
rs.close();
conn.close();
Hope, It would help for you…..
The code is working but i ran into a small problem after that. there are functions i have written whrn there i click on the values that come form the database but after implementing the code the functions dont seem to work. when i say function i have written an on click event for the values that come on the page so if i click on a value the a query is passed and some values are returned to me this does not happen now.
if you dont mind can i send you the file i am working with just view it and tell me where i wne t wrong.
…
Spike
>>if you dont mind can i send you the file i am >>working with just view it and tell me where i >>wne t wrong.
Yeah. sure. it’s better..
I think, you are john. right? cuz i noticed that ur ipaddress and john’s address are the same..
How do you know John :) …. John haug? if its the same person he is my friend and we studied to gather the same IP address could be because its a cafe (browsing center.) anyways Mike i identified the error it was a rs issue I was able to fix it myself …..Thanks for the help.
okay.. i see…
>>anyways Mike i identified the error it was a rs >>issue I was able to fix it myself …..Thanks for >>the help
Your welcome. Spike.
Hi Mike just wanted to know one thing is it possible to call java API’s from a java script. Basically if instead of using straight forward SQL querys to the database use API’s created in JAVA to call them on your webpage using javascript. which is the best option for this purpose. also if you have some examples this would be great.
Thanks
Spike
Ajax might be a solution for u..
Here is free training course.. I recommend you that it’s very cool ..
http://www.javapassion.com/ajaxcodecamp/
Hi. Thanks for the good read.
Hi Michael,
very helpful and useful example.
Could the code also be used for adding new records to the database table with SQL ‘INSERT INTO’ statement? Should the locking variables be changed or statement ‘rs.add’ or something be used?
Thanks
Yes.
It’s better if you use “Command” instead of “Recordset” for inserting new data.
Let me know if you still have prob
Hi Mike
Thanks for your suggestions. In fact I managed to get code to work even without using “Adodb.Command”.
So for other readers, here’s the code:
function AddNewRecord() {
var conn = getAdoDb(“ADODB.Connection”);
conn.open(conn_str, “”, “”);
strQuery = “INSERT INTO Table1 (Field1, Field2) VALUES (‘Value1′, ‘Value2′)”;
conn.execute(strQuery);
conn.close();}
Of course you would probably want to have an input text field or two to write in the strings you want to add to database:
Then the third line of the code will be (in IE):
strQuery = “INSERT INTO Table1 (Field1, Field2) VALUES (‘” + document.all.input1.value + “‘, ‘” + document.all.input2.value + “‘)”;
And the strings you entered in the two Input fields will be added as a new record to the database. (You’ll need of course also a submit button with action or onclick property set to ‘AddNewRecord()’.)
Thanks again for your example and suggestions, Mike, and I hope this code too will help someone of the readers.
Gorazd
Thanks a lot. Gorazd.
My issue is that I am using .net dll (with com interface enabled for asp pages) and I need to do runtime calculations based on customer input parameters.
Lets say I want to do this in javascript.
x= “test” //value entered by customer on form
function GetData(x)
{
call DB(x) //toget database data
write response on asp page
}
One solution i thought of is using a record set and filter it with value “x” and write the response on asp page (thats why i cam on you site.
Another solution is to hard code the value of test and get data by calling asp method that calls .net dll and writes the response (its working for me but its no good to me).
Another solution is to use remote java script but i assume it would require to install remote scripting on clients as well which is not any good thing to do.
What do you think? any solution?
thank you for your time.
regards,
Kamran
I also dont want to expose sqlserver password in javascript (I am new to javascript not java) so I assume using recordset in javascript would expose the connection string.. ………….weird…
yeah… it is just a demostration of how things can be done with javascript.. it is not good practice to use that way in real project….
Hi Michael,
This is Extremely Useful article for Client Side DB connection.
Your work is really appreciable
This could be more better if it works in Mozila/Firefox.
any idea for Firefox?
Thanks & Regards,
Chirag Modi
Firefox doesn’t support any ActiveX object by default…..
Check-out this plug-in
http://www.iol.ie/~locka/mozilla/plugin.htm
I haven’t tested yet since I don’t have the FF version that match with this plug-in..
Does anyone realize that putting connection strings as in the above javascript opens your username and password to the world?
Just a though.
Hi Emeta,
You are absolutely right about that. The main reason why I post this is that I wanna show how to connect db from JS code. I already mentioned about that in previous comment.
hi Michael,
Thanks for ur article.it is very usefull for me.i have use this with asp.net,it works.i want to connect to sql server,i tried but it is not working .can u please help me?
thnx in adv,
rajesh
hi Michael,
dont mind my preivios message.it works now.
with regards,
rajesh
okay.. good. :)
hi!Michael,can i ask u sth regarding js connecting with an ms access database?
what i want to do is to insert sth like a jump menu. the contents in the menu are from one particular column of the db say Name. then i created a table below the menu, displaying the other column content in the same row (like the name of a student, followed by his phonr number, home address..). my request is that every time i choose one name from the menu, i can get the returned details from the db in the form i created within the same page.
can i achieve this using js?
Yes. It’s possible to do. Please read all previous comments. I think someone ask the same question before. You can get the sample file (something like master/detail things) in my previous replies..
thanks for ur reply!
i didnt expect that u could reply me…^^
i’ll read thru the whole page and see if i can get the answer.
Hi Alice, Of course. I used to reply every comments as soon as I can. This is my respect for my blog reader. :) I hope you will get the answer.. :) Good Luck!
thanks a lot!I thought it was so old that u wouldnt reply~~^^ u r so kind!:D
there is sth confused me…
i still cant find out how did u manage to make it.
the difficulty i met is the returned value should be returned are not displayed correctly…
ps: i’m using dreamweaver to develop a website…but it should be ok to use js as programming language.
Hi,
I think you can take a look this sample.
Anyway, As I said so many time before, it’s not good idea to use Javascript for connecting database. This code is NOT cross-browser. The best way would be “Using Ajax + Server-side code (e.g. PHP, ASP.NET or Java or etc. )”
Hi, thank u for the advice.
For me now, i’m using dreamweaver to develop a website. It’s easy to setup a jump menu…the prob i met is that i can not get value returned from my database when i select sth in the menu.
so that’s why i’m thinking about using a script to develop what i want…
and my friend saw this page and told me to have a look at it…after looking thru it, i found all were about js, that’s why i’m asking sth about how to use js to achieve my goal.
but if there is a better way, i think i should try it out…
so…do u have any suggestions?
thanks!
i run and studied the sample u gave me~
but there is sth difficult for me to modify, so that i can use in my application.
i have 1 table (not the multiple-table db as in ur sample) in the database including all datas that may be used. i dunt noe how to convert the application to that when i select one option from the jump menu, the other info in the same row of the same table in the db comes to the table in the webpage, as the one shown in ur sample
hi…are u there?
i really need ur help…
i’m dealing with it for 2 days…nothing was done..
Hi Alice,
Sorry for late reply. I didn’t get the notification of your message.. maybe.. something wrong with my mail server.
No. This is where Ajax comes in. You can invoke the web service or other types of server-side script from Javascript using XmlHttpRequest Javascript object. The server-side will query the data from database and it will return as JSON or XML to Javascript. So, you get the data from database in client-side.
Using Ajax is the best solution and it will work in any browser. Using ActiveX object that I used in my sample doesn’t work in other browsers.
You can use the similiar code. I can’t provide the exact code but I’m sure that you won’t need. You can get the idea from the code and figure out how you can use in your way.
Here is the sample code.
var varMenuId = 1; //This is the variable where you have to put the menu id
var strHtml =””;
strHtml += “”;
var conn = getAdoDb(”ADODB.Connection”);
conn.open(conn_str, “”, “”);
var rs = new ActiveXObject(”ADODB.Recordset”);
//We are doing querying data based on menuId
strQuery = “SELECT RowId FROM Table1 WHERE MenuId=” + varMenuId;
rs.open(strQuery, conn, adOpenDynamic, adLockOptimistic);
if(!rs.bof){
rs.MoveFirst();
strHtml += “”+ rs.fields(0).value +””; //result strHtml = “a”
rs.MoveNext();
}
}
else{
//No Records.
strHtml += “”;
strHtml += “no data”;
strHtml += “”
}
rs.close();
conn.close();
Let’s there are three menuitems called menu1, menu2 and menu1. If you click menu1, you want to show the sub-menus based on what you selected (menu1 in this case)
thanks for ur code.
but when i applied it to my script and displayed it in IE, there was an error:
Error Type:
Microsoft JScript compilation (0x800A03F6)
Invalid character
/sdhwo/test.asp, line 101, column 13
var strHtml =””;
————^
And this is my whole script for the jump menu:
DDF
<option value=”">
0) {
if (!Recordset1.BOF) Recordset1.MoveFirst();
} else {
Recordset1.Requery();
}
%>
0) {
if (!Recordset1.BOF) Recordset1.MoveFirst();
} else {
Recordset1.Requery();
}
%>
0) {
if (!Recordset1.BOF) Recordset1.MoveFirst();
} else {
Recordset1.Requery();
}
%>
why the script was not displayed correctly?
so strange
can i send my script to u via email?
because i am too new to js, maybe there is so code i understood or applied wrongly…
Hi Alice,
I have mailed you.. thanks.
i’d say that really really thanks for ur help!
i’d like to say sth abt the asp file.
because some of the code was automatically written by Dreamweaver, so it might be long and messy.
again, thanks for ur help
the prob now for me is the error
Microsoft JScript runtime (0x800A138F)
Object expected
for the line of: var conn = getAdoDb(“ADODB.Connection”);
Hi Alice,
Are you using window? Do you have Microsoft Visual Studio installed? I think some components are missing in your system. maybe, you need to install Microsoft Data Access Components (MDAC) 2.8. You can get it from this link
For me, I didn’t need to install separately since I already have VS6,2005 and 2008 installed in my machine.
i only have iis in my computer. it is said that to run an asp file, the iis is enough.
btw, is the script working on ur computer?
hi, when i tried to install it, there was a popup window saying that all that r part of windows
hi…r u there?
i have struggled for another 3 days…
adn still got a lot of errors…
the most frequent one is Microsoft JScript runtime (0×800A138F)
Object expected
so sad about this…