Insert into MSSQL from Javascript error with activeXobject - javascript

I am building a dummy application for testing javascript and mssql connections, ive done a similar process using c# and now tried to find a way of doing it with javascript, i found the activeXobject online and just figured out it only worked with IE not chrome.
Not sure what other objects i can use that would work here, i simply want to insert a row into the db while using simple html5 and javascript.
Here is what i have to far...
function persistInDB(){
/* Getting access to the database */
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Data Source=SQL5036.HostBuddy.com;Initial Catalog=DB_A1F3FA_dominicmazur;User Id=--MYID--;Password=--MYPASS--;";
connection.Open(connectionstring);
/* JavaScript obect to access a SQL query's results */
var rs = new ActiveXObject("ADODB.Recordset");
var sql = "INSERT INTO DB_A1F3FA_dominicmazur.dbo.Orders (SIZE,CHEESE,PEPPERONI,HAM,PINEAPPLE,SAUSAGE,FETA,TOMATOE,OLIVES,SUBTOTAL,GST,TOTAL) VALUES ('"+size+"','"+Cheese+"','"+Pepperoni+"','"+Ham+"','"+Pineapple+"','"+Sausage+"','"+Feta+"','"+Tomatoes+"','"+Olives+"','"+cost+"','"+GST+"','"+grandTotal+"')";
alert(sql);
rs.Open(sql, connection);
/* Closing the connections */
//rs.close;
connection.close;
}
Thank you in advance :)

There's no good reason to try to do this from a browser, unless you have some absurdly niche requirements. (And any such requirements would probably be better questioned than followed!)
Collect the data on a form and send it to your server using HTML5 & JavaScript, and then do the database operation/s from there.

Related

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

How to fetch data from SQL database using TruClient protocol

During my load test, I would like to fetch values from an SQL database. How can I achieve this on load runner TrueClient protocol using JavaScript?
This would be great help…
Important: This will only work in TruClient (IE) and not in TruClient (Firefox).
Enter a new "Eveluate Javascript" step, and edit the javasctipt like so:
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
// Here you should get the value from the 1st cell, 1st column
var value = rs.fields(1);
rs.movenext;
}
rs.close;
connection.close;
There are several options.
I'll list them in order of their complexity:
Option 1:
Use a parameter file to hold all of your data. If you need to modify it periodically, consider placing it in a shared location, accessible for all LGs.
Option 2:
Use the Virtual Table Server (VTS) provided with LoadRunner. It is dedicated to sharing test data between virtual-users. Queries are easy with a built in API.
Option 3:
You could write a custom C function, using LoadRunner DB API to query the DB, calling the function from your script using an Eval C step.
Note this can only be done in VuGen.

Boostrap modal form with 2 submit buttons and save in database

I am trying to make a form on a modal. I have a form with 2 buttons: accept and reject.
If the user clicks on accept there is an update in that database, if the user clicks on reject there is another update.
I need to retain a certain value from database before, so I am making a select.
The problem is that I don't know how to make an insert in database using javascript (I know it is possible with jquery/ajax but how to call
it in the button?).
Here is my code:
Here is the Javascript function to insert in database that doesn't work
<script type="text/javascript">
function clicked1() {
//update candidate_jobs SET is_hired='1' WHERE candidate_id=$userId and applied_to=$row["job_id"];
var connection = new ActiveXObject("ADODB.Connection"),
recordSet = new ActiveXObject("ADODB.Recordset"),
connectionString = '';
connection.Open(connectionString);
recordSet.Open(
"update candidate_jobs SET is_hired='1' WHERE candidate_id=".$userId." and applied_to=".$row["job_id"]."";,
connection);
recordSet.close;
connection.close;
alert('You accepted the offer');
}
function clicked2() {
//idem clicked1 but change the is_hired value to be inserted in the database
alert('You rejected the offer');
}
</script>
Can it be done using Jquery and Ajax? How?
What it wrong with the code?
Thank you very much!
The concatenated sql string is prone to sql injection attacks (although obviously anyone viewing the page source can do whatever they like to the database anyway) - parameterization is the solution here and we need to use an IDENTITY or GUID.
Here is a list of possible issues:
1) The code will only ever run in IE browsers
2) You may need to download and install the COM components - ADO
3) You may need to run IE as an Administrator
4) You may need to open all sorts of security loopholes in IE (ActiveX controls, safe for scripting etc)
If you enable script debugging on the browser you'll get more info on the actual issue.
hope it helps you.

SQL.js in javascript

I want to store data in a SQLite database directly from a javascript script. I found this SQL.js library that is a port for javascript. However, apparently it's only available for coffeescript. Does anyone know how to use it in javascript? Other ideas about how to store data in SQLite DB are welcomed too.
Update
sql.js now has its own github organisation, where both the original author and I are members: https://github.com/sql-js/sql.js/ .
The API itself itself is now written in javascript.
Original answer
I am the author of this port of the latest version of sqlite to javascript: https://github.com/lovasoa/sql.js
It is based on the one you mentioned (https://github.com/kripken/sql.js), but includes many improvements, including a full documentation: http://lovasoa.github.io/sql.js/documentation/
Here is an example of how to use this version of sql.js
<script src='js/sql.js'></script>
<script>
//Create the database
var db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
// Insert two rows: (1,111) and (2,222)
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);
// Prepare a statement
var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}
// Bind new values
stmt.bind({$start:1, $end:2});
while(stmt.step()) { //
var row = stmt.getAsObject();
// [...] do something with the row of result
}
</script>
I'm using SQL.js from pure JavaScript without any problems. Simply include the following file:
https://cdnjs.com/libraries/sql.js

Local HTML 5 database usable in Mac Dashboard wigdets?

I'm trying to use HTML 5's local database feature on a Mac Dashboard widget.
I'm programming in Dashcode the following javascript:
if (window.openDatabase)
{
database = openDatabase("MyDB", "1.0", "Sample DB", 1000);
if (database)
{
...database code here...
}
}
Unfortunately the database-variable remains always null after the call to openDatabase-method. I'm starting to think that local databases are not supported in Widgets...
Any ideas?
/pom
No you will not be able to do the above. And even if you could then you would not be able to distribute the widget without distributing the database assuming it was a MySQL or SGLite. (not sure what you mean by HTML 5's local Db.
here are a number of ways round this:-
You can add a data source which can be a JSON file, or an XML file or and RSS feed. So to do this with JSON for example you would write a page on a server in PHP or something that accessed a database so that when the URL was called the result was a JSON string. Take the JSON string and parse it and use it in the Widget. This will let you get data but not save it.
Another way would be to use the user preferences. This allows you to save and retrieve data in the individual widget.
So
var preferenceKey = "key"; // replace with the key for a preference
var preferenceValue = "value"; // replace with a preference to save
// Preference code
widget.setPreferenceForKey(preferenceValue, preferenceKey);
You can then retrieve it with
var preferenceForKey = "key"; // replace with the key for a preference
// Preference code
preferenceForKey = widget.preferenceForKey(preferenceForKey);
The external call, you could also use REST will let you read any amount of data in and the preferences will let you save data for later reuse that will survive log out's and shut downs.
The Apple site has a lot of information about Widgets and tutorials as well thjat are worth working through.
Hope this helps.

Categories