h m
h m

Reputation: 11

function to search database for keywords

trying to get functionality to search a mysql database for keywords using javascript, running into problems with how to execute the commands in js and how to insert the keywords from an input box to the mysql query.

<html>
<head>
<title></title>

<script> function mysqlList(){

var keyword = document.getElementById('keyword').value;


var mysql = require('mysql');


var connection = mysql.createConnection(
{
host     : 'localhost',
user     : 'xxxxxx',
password : 'xxxxxx',
database : 'joblist',
}
);

connection.connect();


var queryString = 'SELECT name, trello FROM graduates WHERE (name LIKE '%keyword%'    OR trello LIKE '%keyword%');

connection.query(queryString, function(err, rows, fields) {
if (err) throw err;

for (var i in rows) {
var console = console.log('name: ', rows[i].name, '|',  'trello: ', rows[i].trello);
}
});

connection.end(); 
};

window.console = {
log: function(str){
var node = document.createElement("div");
node.appendChild(document.createTextNode(str));
document.getElementById("myLog").appendChild(node);
}
}

</script>
</head>
<body onload="onload();">
<input type="text" name="enter" class="enter" value="" id="keyword"/>

<button onclick="mysqlList()">run query</button>



<p id="myLog"></p>
</body>
</html>

this is non functional at the moment, but even if anyone could point me in the direction of some good tutorials I would appreciate it.

thanks!

Upvotes: 1

Views: 649

Answers (1)

user149341
user149341

Reputation:

You can't do that.

First: require() is specific to NodeJS. It is not available in the browser. Some of the modules which can be loaded with it are available in the browser, but mysql is not.

Second, and related: You can't connect to a MySQL database directly from a web browser. Javascript running in a browser can only make HTTP connections to web servers, and even then only on a limited basis.

You need to implement an API on the server -- possibly using Node, possibly something else -- to perform a search. Then you can use the XMLHttpRequest browser API -- or something based on it, like $.ajax() in jQuery -- to call that API.

Upvotes: 1

Related Questions