1

I know that for connecting to the database from JavaScript I need to mention the database credentials in plain JavaScript code. Therefore for a online application that would be a huge security risk. But in my case I want to write a small JavaScript application which is stored locally. So the credentials won't be shown to the world but just to the user I give the application, which is acceptable for me.

The motivation behind this is that I want to connect to an online database without a running PHP server, just from a JavaScript embedded in the local page. My goal is to provide an application that can be run by the user without the need for PHP and a server, except the database server. It's similar to a desktop application but running in the browser.

How can I connect from JavaScript to an online MySQL database? All other similar questions I found on Stack Overflow advices the thread starter against this usage for good reason but hadn't answered the question.

I heard that connecting to MySQL from JavaScript would be impossible. But how do, say, Windows 8 Metro Apps written in JavaScript handle that issue?

danijar
  • 32,406
  • 45
  • 166
  • 297
  • Possible duplicate: http://stackoverflow.com/questions/3020751/can-javascript-connect-with-mysql – sanchez May 29 '13 at 17:01

2 Answers2

3

A backend repeater is always needed. For this issue you can set up a light-weight server that forwards your database accessing request to mysql server using, say node.js.

kyriosli
  • 333
  • 1
  • 6
  • So I need a server side script that expects the user, password and query of the MySQL database, so that the server sends the request? Why can't I send the request directly from JavaScript? It seems like there is no technical limitation to me. – danijar May 29 '13 at 17:13
  • For security reason, JavaScripts running in a browser has very limited access to a local files/devices/something else, and there is no possibility creating a generic socket connection to a mysql server by mysql. – kyriosli May 29 '13 at 17:17
  • I tried that but I cannot send ajax requests to the server script since that would be cross site scripting from the JavaScript that is local. – danijar May 29 '13 at 18:00
1

If you are focussing on a specific web browser, maybe you'll find a workaround. But if you're thinking on a local application independent from the user agent, you should follow the standards to reach a predictable behavior (or at least the best approach). In the W3C standards you have two options for storage:

Web Storage API: you're limited to key-value storage, but is very well supported.
Indexed Database API. I've no experience with it, but it's supported.

If you're not to limit the user context to a restricted machine and user agent, you can start with standard storage solutions as mentioned above and then enhance your app for more advanced browsers (perhaps even with MySQL!), as recommended in Progressive Enhancement

eleuteron
  • 1,863
  • 20
  • 26