How to use JavaScript/Ajax and Python to edit local SQL database? - javascript

I've developed the front-end of a web site using JavaScript.
I have a button that when it's clicked retrieves an integer value from another object on the website.
I have a local SQL database. How do I make SQL calls when this button is clicked?
I've seen answers with JavaScript/Ajax and PHP, but I don't want to use PHP.
Using JavaScript only, can I open a local SQL db and make SQL calls? If yes, how?
If I can't do this using JavaScript only, can I use JavaScript/Ajax and Python? If yes, please post a reference or simple example.

Technically it is possible to connect to a database using client-side JavaScript. However, as others have already pointed out, doing so is considered to be really bad practice for a few reasons - the most important of them being security.
When the browser is asked to load a certain page it will go ahead and ask the server for the content that is found at that URL. This means HTML files, external JavaScript files, images, stylesheets and other resources that are needed in order for the page to get rendered. Since the user has access to the these files, especially your JavaScript code, it means he has access to your database credentials. You could try to minify/obfuscate the code, but that won't make it any safer.
If you do understand all the consequences and for some reason you still want to do it, take a look at this example.
The best way to go at it is to have a server handle the interaction with the database. Depending on your language of choice, you could build that part of the application using PHP (among with an HTTP server such as Apache), Java, Python and so on. You could even use JavaScript (see Node.js).
Since you asked for a Python snippet, here's one that connects to a MySQL database and creates an HTTP server that listens for connections on port 8080. For each GET request it will receive, the script will query the database and send back the result as text/html.
#!/usr/bin/python
import MySQLdb
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method
data = cursor.fetchone()
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(data)
return
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="yourpwd", db="pw_exam")
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()

You can't do this from the javascript in the browser for a simple reason - if your database is available to your javascript code, it is also available for any web site user. And someone will just delete all your data or will replace it with something funny.
That is why we usually also have the server-side application and it can basically be in any language - php, python or javascript.
And there are frameworks and libraries to simplify your job also for any language.
For example, for python you can use flask and sqlalchemy.
If you want javascript everywhere, then use nodejs on the server and expressjs as server-side framework is one of most popular options for node. And you can find node.js packages to make SQL queries to your database too.
The general flow of your application can look like this:
Your client-side application is opened in the browser and it needs some data from the database
It sends the AJAX request to the sever
Server makes a database request and returns the data as json
Client-side application displays this data
It works similar when data need to be modified.
The difference here is that your database is "covered" by server side, so you can be sure that only allowed operations are performed.
Like nobody is able to drop the database, or only a registered user can edit the profile data (and only own profile data editing is possible), etc.

JQuery is a brilliant way to create live Database feeds in Website development. You can simple import the JavaScript files from CDN or Google or download and use it here: https://jquery.com
Front end:
$(document).ready(function(){
$("#idHere").click(function(){
var testdata = document.getElementByID("#idHere").value;
var anothertestdata = document.getElementByID("#idHere").value;
$.ajax({
url: "/inc/Database.php",
data: {
example: testdata,
anotherexample: anothertestdata
},
success: function( data ) {
$( "#idHere" ).html( "<strong>" + data + "</strong> " );
}
});
});
});
PHP file:
if(isset($_GET['testdata'])):
$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
$query = "SELECT * FROM TABLE";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)):
echo $row['CollumnName'];
endwhile;
$db->close();
endif;
Anything echo'd will show in the response.
Using JavaScript to open a Database is hard, long and has MANY security issues. I would not recommend in doing so.

Related

Inserting into MySQL database with javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently working on a school project and I need some help. I ran into a problem when trying to put the data I read from another IP address (using AJAX) into a MySQL database. I tried using node.js but because I'm calling the function when I press the button on a webpage it doesn't work... So any suggestions or tips on how to make node.js work.
ajax function:
function AddShoots() {
$.ajax({
method: "POST",
dataType: "json",
url: "http://192.168.1.8",
success: function (html) {
for ($i = 0; $i < html.length; $i++) {
console.log(html[$i]);
}
},
});
}
The data I get and would like to insert into database:
EDIT: additional explanation
sorry for the HTML/CSS there was an error while copying. To clarify my endpoint I have a python image recognition program written on raspberry PI, the Raspberry PI server that is on the IP returns the numbers seen in the picture, I would like to insert the numbers into a MySQL database and I need help with how to do that because I only inserted data into tables with PHP before, but I can't do this in this case because I'm using AJAX (at least not with my knowledge) I hope this explains everything better.
Another edit:
A picture that might help with understanding (I'm super bad at explaining sorry English is not my primary language that's why I have bad expressions and a hard time explaining some stuff).
Sounds like you're getting your technologies mixed up a bit.
Lets clarify a few terms first:
NodeJS
Is a JavaScript runtime for server-side or backend code.
Runtime
An environment for code to execute like NodeJS or a web browser.
Server-Side
This refers to code running on a server. Could be PHP, Java, Python etc... or even JavaScript if you're using Node.
Backend
Usually means the same thing as "server-side" when people say "backend".
Frontend
In this context, "frontend" is referring to code being executed in a web browser.
AJAX
A style of HTTP request that a browser can use to send and fetch data without reloading the current page.
Now that we have that out of the way...
Node is a server-side runtime for JavaScript, so your JS code running in the browser has no way to talk to your Node code directly.
If you want to click a button in the browser and see data get written to your database you have to make an AJAX call to a url that your backend is listening to (known as an endpoint or a route).
It's a bit difficult to interpret your intentions from your example but I think you mean to send a POST to http://192.168.1.8. So you'll need a route configured in your Node app that can handle the AJAX request, and from there you can write the data to your database.
Of course you'll also need to pass the data with the request. That gets passed along with the options parameter in your $.ajax(/* ... */) call.
At a high level this is what I believe you're trying to achieve:
So basically your app should have at least two files:
index.html This will have your button as well as the JS code that fetches data from your Pi. This "front-end" JS will also have to send an AJAX request to your Node app.
app.js This will be your Node app. It will have to expose an endpoint that your front-end code can send data to. Inside the function of that endpoint, you'll handle writing the data to your database.
There's a library called Express that will help you make your endpoint. I recommend following their Getting Started guide: https://expressjs.com/en/starter/installing.html
Update
I see you updated your answer with a diagram. I assumed your mental model was probably exactly like that, which is why you're having a hard time.
When a user visits a url such as https://stackoverflow.com for example, the request doesn't go to the web browser. The request has to go through a server first. When you use Node, your app essentially is the server, and is responsible for returning the correct response.
In your case the response would be an HTML file like index.html for example.
That index.html is the webpage and it is going to contain your "front-end" JavaScript code, which can communicate to your Raspberry Pi server over HTTP to get that image data you're talking about.
JavaScript running in the browser has no way to communicate to a SQL database directly. So you have to send a request over the network to your Node service. Inside your backend application you can write the data to a MySQL database with the help of packages you can get from NPM. Here's an example of one: https://www.npmjs.com/package/mysql
Update 2
It sounds like you're more comfortable using PHP. You can swap NodeJS out with PHP and my diagram would still represent what you want to achieve at a high level. The key difference is you won't have to figure out how to set up a "route".
With PHP you can just have a file named something like SaveMyData.php:
<?php
// Get the body of the POST request
$data = file_get_contents('php://input');
// Decode the JSON string so you can work with it in PHP
$decodedData = json_decode($data);
// $decodedData is now an array of the data you sent from the browser
foreach($decodedData as $row) {
// write the row to your database here
}
Then the "endpoint" (making some assumptions about how your serving your app) is just http://localhost:8080/SaveMyData.php and that becomes the URL you pass to your AJAX call from the browser.
Your AJAX request would look something like:
function AddShoots() {
$.ajax({
method: "POST", // the post to your Pi I'm assuming?
dataType: "json",
url: "http://192.168.1.8",
success: function (data) {
$.ajax({
method: "POST", // this is going out to your PHP backend
dataType: "json",
url: "http://localhost:8080/SaveMyData.php",
data: data,
success: function (response) {
// do stuff with the response if you'd like
})
});
},
});
}
Tons of "best practices" are being violated here, but for the purposes of a school assignment this should get you pointed in the right direction.

fetch data from mysql db with js or java, no php usage

which is the best approach to open connection to a db that is on another domain with js, java.
Example, im using gtm to push data to a datalyer, all i have is front-end access, but i have access to the data base on another domain, how can i fetch the data from the other data base to gtm when gtm only allows js no php coding, so the date can be dynamic since the data that i need to push is coming from the external database.
Thanks in advance
<script>
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)
{
document.write(rs.fields(1));
rs.movenext;
}
rs.close;
connection.close;
dataLayer.push({
'usersigendup': 'some-value',
'productID2': 'some-value2',
'productID3': 'some-value3',
});
</script>
The above code isnt working, but basically how can i accomplish that "some-value" become the result of a value fecthed from the DB.that is what i found so far googling
GTM has no serverside API for tracking, so you cannot send data directly (also you do not want to give database credentials to a client-side script).
You could create a serverside script that fetches data from your database. Then you make this available via an URL that returns the database result. Then you create a custom HTML tag with a JavaScript that connects to your new endpoint, fetches the response and parses it into variables that you then use in your tracking tags.
You would need to make sure that your script still works (or terminates properly) when there is no response from your endpoint.
Simo Ahava demonstrated the technique in an older article of his, the only difference is that instead of using an availaibe webservice like the weather API you would have to create your own service that returns your database results.

Javascript - create text file on website

So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.
e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt
Is there a way to do this with HTML/Javascript?
EDIT:
I am on Github
You can't do it with HTML/Javascript alone, you need a functional language on the backend (nodejs, php, python)
You can use ActiveXObject, but it won't work in all browsers.
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
https://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx
If, when you say "JavaScript", you're referring to a node.js application running on a server, then this is possible. It doesn't have to be node though; it could be a Django site, or an ASP.Net site, doesn't matter. You can't have JS code in the browser create files on your server... the JS in the browser is executing on a client machine, and doesn't have access to the server's file system.
You could create an endpoint to which your clients could send requests that would initiate the creation of the file.
You could also allow clients to PUT or POST files to your server, but again, this is something you control from the server side of the application. Your webpage (i.e., HTML file as you put it) cannot create files on the server itself. Your server allows clients to send it files in a specific manner, and the client must adhere to those rules.
The short answer to your question is no.
The long answer is that you have the following alternatives:
Use a form on the Browser end, send the data back to the server, and then use a server-side language such as PHP to receive and save the data. No JavaScript required, but you do need server-side programming.
You can make the process more immediate by using JavaScript on the browser end to send data back to the server. This is called Ajax. You will still need server side processing, though.
Note that it is probably a very bad idea to simple accept user data and save it directly. There are two things you should consider in your development:
Always filter the incoming data against the possibility of receiving and accepting carefully crafted malicious data.
Consider storing the data in a database. Apart from being easier to manage (you don’t have to worry about filenames, for example), they can do less damage there.
You can achieve this in IE browser using the following code.
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
if you are looking for a goos reliable solution then better to use PHP and other server scripts.

Getting php data from database using jquery without ajax

I am developing a query PHP enabled chat, currently am using ajax to pull data from the server and display it in the chatbox but this makes use of multiple ajax requests to the client computer which causes it to slow abit....
This is what I am doing using ajax and yii2
function getdata() {
$.get("controller/action").
done(function(){
//process json
$("#chatbox").html(data);
})
}
then am using
windows.setInterval(getdata(),1000);
Are there better ways to fetch this son data without using ajax and jquery
I have checked on This link buts its not very helpful
You can use socket.io or websockets api which is an alternate option to ajax, So, by using socket.io, jquery, php OR nodejs one can build one to one private chat without using ajax, following links will help you out how to build private chat.
socket.io
WebSockets
Private chat reference 1
Private chat reference 2
A better approach is using nodejs instead of php. You can check this link for a really nice implementation of chat which you can use.
While php chat has performance issues like you mentioned, nodejs doesn't because instead of polling the messages it pushes them to the client when there is something to push. And also you receive ready to use solution right out of the box (of course you have to modify it) which will save you development time.
But if you still want to go with the php way, then you have these options:
jquery + ajax (like you are doing it right now)
php sockets - here is an example of php chat using websockets https://www.sanwebe.com/2013/05/chat-using-websocket-php-socket. This approach has its pros and cons. One of the major cons is that is not supported by old browsers and may be the setup process is not that easy. But I'll prefer it over the ajax requests.
You mention getting data from the database, but one could argue that, for the purpose of a chat application, the database is incidental. Maybe you want to store the chat history and the database is a natural place to do so, but the primary functionality is to transmit messages. So you are using the database as some kind of message buffer.
Websockets seems the best option, as others have mentioned. If you want PHP server-side, in addition to the Kraken framework as mentioned in a comment to your question, you can take a look at the Ratchet library. They have a tutorial for a simple chat in their site: http://socketo.me/docs/hello-world
Basically, you need another server-side process (in addition to your webserver) to receive and broadcast the chat messages. Following that tutorial, in the onMessage method of the Chat class you can do the insert in the database if needed, preferably asynchronously.
Client-side, you will need to connect to the websocket using Javascript. Simple example:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log('Message received: ' + e.data);
addMessageToChatbox(e.data);
};
$('#yourChatInput').keypress(function(e) {
if(e.which == 13) { // "enter" was pressed
conn.send($(this).val());
$(this).val('');
}
});
function addMessageToChatbox(message) {
//
}
You can do a trick, suppose data is not json it is javascript file declaring single variable now you have to add it to document such as
below is your data.php(javascript generated by php)
in php
echo 'var x = {"name":"Anshuman"}'
In javascript
var s = document.createElement( 'script' );
s.setAttribute( 'src', 'data.php');
s.onload=callback;
document.body.appendChild( s );
function callback(){
console.log(x);
}
There aren't any sensible ways. You have to bring the new data in somehow right?
The to ways to do that are by reloading the page or by Javascript / Ajax to avoid the reload.
You could make the update one sided so that when Person A writes to person B the request is performed on the submit of the new message. This would mean that no new messages are retrieved unless one is sent. (Not practical)
Another method would be to have a last message time noted somewhere on its own and you could repeatedly check for that.
Should that time change you could fetch new data then but that would not fix the amount of requests... only the amount of data being transferred.
I suggest you look at the size of the data from the json/php. Have you ran tests to see how long that is taking or how it is performing?
I could refer you to this post which is using NON jquery requests if you like.

Swap Existing Javascript SQL Server Connection with Server-Side Connection on ASP.NET?

The client machines do not have access to the SQL Server port and opening the port to the client machines is not possible.
Scenario: We have an old client application written entirely in javascript. The javascript contains a clear text connection string, including a sql server account username and password. We also use ASP.NET to host other applications.
We were hoping to move the connection to the server without having to rewrite the entire javascript application.
Is there a way to just replace the connection in the .js file with a server-side connection without having to write AJAX (or something similar) calls for every data function in the .js files?
Here is how the clients used to connect before the SQL Server port was changed:
var conn_str = "DRIVER=SQL SERVER;SERVER=MyServer;DATABASE=MyDb;UID=sqluser;PWD=mypassword;";
function openConn() {
//alert("openConn() ");
this.conn = getAdoDb("ADODB.Connection");
conn.ConnectionTimeout = 240;
conn.CommandTimeout = 240;
conn.open(conn_str, "", "");
//alert("Current Connection String: " + conn_str);}
The above code is in a javascript file with thousands of lines of code. We'd like to simply replace this connection part of the javascript with something on an ASPX page or AJAX or something that could be consumed by the .js file.
Is there a way to just replace the connection in the .js file with a server-side connection without having to write AJAX (or something similar) calls for every data function in the .js files?
If you are going to use server side technologies, AJAX is just one option. You can embed the retuned data in your pages to be consumed by javascript (ie. output JSON to the page) etc.
You can create a generic server side data function that will accept the SQL and parameters, but will need to validate the passed in queries and parameters to avoid SQL Injection and tampering.
In my opinion, there is no secure way around replacing all the data functions.

Categories

Resources