1

I'm trying to connect and request queries from my database, but I wanna do it with JavaScript (or jQuery).

I'm trying this:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "myUser",
  password: "myPassword",
  database: "mydb"
});

function GetSqlResult (sql_query) {
  con.connect(function(err) {
    if (err) throw err;
    //Select all customers and return the result object:
    con.query(sql_query, function (err, result, fields) {
      if (err) throw err;
      return result;
    });
  });
};

But I get this error:

Uncaught ReferenceError: require is not defined

I've tried using using the module "require.js" from this website http://requirejs.org/docs/release/2.2.0/minified/require.js

I still got the same error.

I want a solution for this error (if it exists), not an alternative.

I know that connecting to a database from JavaScript isn't very safe, but I really wanna do it, so I would love for someone to help me, please.

Thank you

4
  • node.js != jquery Commented Apr 21, 2018 at 0:25
  • NodeJS code does not run in your browser, it runs on a backend web server. You should run this code using Node. See nodejs.org/en/download to set it up. Commented Apr 21, 2018 at 0:27
  • @Kulix what can i do? Commented Apr 21, 2018 at 0:28
  • possible duplicate of stackoverflow.com/questions/3020751/… Commented Apr 21, 2018 at 0:29

2 Answers 2

1

What you are trying to do without knowing it, is build a RESTful API. In web architecture, you have your front end code (browser javascript) which makes HTTP requests to a backend. That backend will connect to the database and run queries. Even if you wanted to do this from browser javascript, your browser wouldn't let you. I would recommend you write a REST Api using NodeJS, and have your browser javascript make HTTP requests to that backend. Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

NodeJS is not jquery, nodeJs it runs on a backend web server.

you can use Meteor for connecting to database from the client side.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.