Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Data from Node.js file and displaying it in HTML/JS page

I am new to Node.js and this is my first project with it. I have made a node.js file named test.js. It has an array say a.

Now I want to make a HTML file that calls this test.js on button click event. Then get the data from that file and publish it on a table in the HTML file.

I have already written the node.js file and I can see the results on console.log(a). But I cant understand how to send this array to HTML when it will ask for it.

Meanwhile, I googled and made up some code. The request reaches the server but I always get error response from server. Why so?

Client Side -

function fetch() {
    $.ajax({
    type: 'POST',
    url: "http://127.0.0.1:8888",
    data: 'China',
    datatype: 'json',
    success: function (data) {
        alert("hi");
        var ret = jQuery.parseJSON(data);
        $('#q').html(ret.msg);
    },
    error: function (xhr, status, error) {
        alert("hii");
    }
});

Server side :

http.createServer(function(request, response) {  
    console.log("Request received");
    response.writeHeader(200, {"Content-Type": "application/json"}); 
    request.on('data', function (chunk) {
        console.log(chunk.toString('utf8'));
                    consol.log(result);
        response.write(JSON.stringify({data : result}));
    });     
    response.end();  
}).listen(8888);

I can see China on the console.But I dont get back the result array back to the client. Here result is an array and I get its value on the console. Just that I dont get it back to the client. Any help ?

like image 815
Wayne Rooney Avatar asked Aug 04 '13 10:08

Wayne Rooney


1 Answers

You should start by setting up a server to serve requests. I use expressjs for this - http://expressjs.com/

This will allow you to run nodejs as a web application.

Setup a route in express JS to serve your data - http://expressjs.com/api.html#express

var express = require('express');
var app = express();

app.get('/data', function(req, res){
  res.send('hello world'); //replace with your data here
});

app.listen(3000);

Open up a browser, and type in http://MY_SERVER_ADDR:3000/data and you should see your output there.

Next, you'll need to attach an event handler to your HTML file that will trigger a $.get() request when it is triggered. Add the previous url to your data in your $.get call and do something with it.

$('.my_selector').click(function(){
   $.get('http://MY_SERVER_ADDR:3000/data', {}, function(data){
        console.log(data)
   });
});

That should get you going.

like image 181
JohnP Avatar answered Nov 05 '22 20:11

JohnP