Web Analytics Made Easy -
StatCounter Query db within JS function - CodingForum

Announcement

Collapse
No announcement yet.

Query db within JS function

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Query db within JS function

    Hello,

    I'm trying to connect to and query a database using JavaScript (inside a function definition). Here's the function:
    Code:
    function lookupAcct(){
    	
    	
    	var inputName = prompt('Enter company name to search for:', '');
    	
    
    
        var conn = Server.CreateObject("ADODB.Connection")
    	var cst = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:/InetPub/db/XPCT ARTS.mdb"
    	conn.Open cst
    	var rsAcctLU = Server.CreateObject("ADODB.Recordset")
        
    	var sql = "SELECT CustomerName, CustomerCity, CustomerState, CustomerID FROM tblAccounts WHERE CustomerName LIKE '%" & inputName & "%';"
    	rsAcctLU.Open sql, conn, 3, 3
    
    	var alertString = "Below is a list of accounts that matched your criteria\n\n"
    	do while not rsAcctLU.EOF
    		alertString = alertString & rsAcctLU("CustomerID") & " " & rsAcctLU("CustomerName") & " - " & rsAcctLU("CustomerCity") & ", " & rsAcctLU("CustomerState") & "\n"
    		rsAcctLU.MoveNext
    	loop
    
    	alert(alertString)
    	
    	rsAcctLU.Close
    
    }
    Is it possible to use JavaScript to query the database? I've also considered using ASP within the function def, but surrounding my db connection and query code in <% %> didn't accomplish anything. Would very much appreciate any help that can be provided. Thanks in advance!

    -K

  • #2
    JavaScript cannot directly query databases. It has no standard way of talking to them.

    You really don't want to be able to do that anyway. If your JavaScript can do SQL calls you've got serious security issues. Anybody could fashion their own SQL call and abuse your database however they want.

    You need to do your queries on the server side. You can display the data that comes back in your web page without reloading the page if you want. Search for AJAX for more info.
    ScriptingMagic.com

    Comment


    • #3
      Ok, sounds promising. The only thing is I need input from the user in order to make my query (searches account name input from prompt() popup). Is that something that can be done? Thanks for the help.

      Keith

      Comment


      • #4
        Yes, passing variables from your page is the correct way to do it. I wouldn't recommend using prompt() just because it is ugly but that is a quick way to do it.

        Just make sure that you validate the parameters you get from the page before using them in SQL so you don't get hackers injecting their own SQL statements.
        ScriptingMagic.com

        Comment

        Working...
        X