JackSparrow123
JackSparrow123

Reputation: 1380

Display retrieved SQL data to HTML page in Node.js

I have code which retrieves dataset from our database:

var pg = require('pg').native;

// Format: "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";
var dbUrl = "url hidden";

function testConn(onDone) {
    pg.connect(dbUrl, function(err, client) {
        client.query("SELECT ad FROM alert WHERE ad = 132", function(err, result) {

            console.log("ad is: %d", result.rows.length);
            console.log("ad value is: %d", result.rows[0].ad_id );
            onDone();
        });
    });
}

// Let's call the function
testConn(disconnectAll)

// Disconnect all connections
function disconnectAll() {
    pg.end();
}

And this works just fine, it retrieves and displays the results onto the terminal.

What I would like to achieve is to have these results appearing on a html page instead of the console, I've already developed the front-end page (used jquery mobile) and wish to have the database values come up on this page instead of the console.

Can anyone please guide me on the right path on doing this? For instance I know the div element can be used to hide/display data, I just need to know the best way to retrieve and display the results onto an element such as this onto a html page.

Thanks all help appreciated!

Upvotes: 0

Views: 3498

Answers (1)

kobe
kobe

Reputation: 15835

something like this , but this is copy from google only

  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  response.write(
    JSON.stringify({ 
      anObject: otherObject, 
      anArray: otherArray, 
      another: "item",
    })
  );

Upvotes: 1

Related Questions