how to run a MySQL query using JavaScript

Javascript cannot run MySQL Queries itself; however, you can use ajax to make a call to the server to retrieve the data. I like to use jQuery's ajax() for my ajax needs.

Here is an example of how jquery's ajax() method works:

$.ajax({
  url: "pathToServerFile",
  type: "POST",
  data: yourParams,
  dataType: "json"
});

You can't query with pure javascript. It has to be done from a hook that is setup on a backend.

This tends to be done with ajax.

Moreover, if querying were available from client side, then everyone could see your connection string.


You'll need to have a backend script do the query - JavaScript, being an entirely client-side language, has no say-so in what goes on with your MySQL server.

What you'll need to do is pass the parameters you want in your query to whatever server-side language you're using via AJAX, and have the script create and process the query as you wish.

DO NOT create the query in javascript and pass it to the server - this is VERY unsafe as it allows anyone to run whatever queries they want.