carlos E. carlos E. -3 years ago 105
Ajax Question

How to get data with ajax from a query string from a route in Node.js?

Like my title says, I am trying to pull data from a route with a AJAX Request that holds json data ('/home/playback/json'). But this data won't exist unless a query is done But I am trying to incorporate this from my client side page(playback.ejs) but I can't connect a query to my route that is connected to my database. Any ideas or documentations I should try out?

AJAX Request

$(document).ready(function () {
$('#search').on('submit', function() {
$.ajax({
url: "http://localhost:8080/home/playback/json",
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(data);
},error: function () {
alert('error');
},
type: "GET",
});
});
});


Route.js

app.get('/home/playback', function (req, res) {
res.render('playback.ejs');
});
app.get('/home/playback/json', function (req, res) {
//database connection
dbconnection.query("SELECT * FROM myTable WHERE FILE_NUM LIKE '%" + req.query.searchFileNumber + "%' LIMIT 5", function (err, rows, fields) {
if (err) throw err; //Show any errors
var data = [];
for (i = 0; i < rows.length; i++) {
data.push(rows[i]);
}
res.json(data);
});
});

Answer Source

I might be missing something, but wouldn't this work?

$.ajax({
    url: "http://localhost:8080/home/playback/json?searchFileNumber=1",
    ....

Also: watch out for SQL injection vulnerabilities. Without proper user input sanitation anyone could drop your database.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download