0

I want to pass my products array to html page.

app.get("/", function(req, res){
    res.render(__dirname+ "/product.html",{data: Product_Array_fromDatabase});
})

At client side in HTML page am trying to view / will loop it

<script type="text/javascript">
    var data = JSON.stringify(data);
   alert(data) // Says Undefined
</script>

I am not getting value of data? Any help?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40

1 Answers1

1

js i made the ejs to render the data and used jquery ajax to send the data to the page and alert it may be this will useful to you

hello.js

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

var engine = require('ejs-locals');

app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');


app.get('/', function(req, res){ 
res.render('index',{user:"John Smith"}) 
 });

app.get('/helo', function(req, res){
  res.send({'data':'hello'});
});


var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);

});

index.ejs in the directory called views---path appname/views/index.ejs

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("/helo", function(data, status){
            console.log(data);
            var result = data
            alert(result['data'])
        });
    });
});
</script>
</head>
<body>
welcome <%= user%><br>
<button>Send an HTTP GET request to a page and get the result back</button>


</body>
</html>
zabusa
  • 2,520
  • 21
  • 25
  • Do we have to use same method after emit / broadcast? i.e. Loop using <%= %>... I am not much familiar with this tag... can we use jquery/javascript just to loop? – Mangesh Sathe May 16 '15 at 13:10
  • <%= %> tag used to print varibles in the html page....in ejs..its a templating engine used in express. <% for(var i=0; i < data.length; i++) { %> <% } %>
    <%= data[i].id %> <%= data[i].name %>
    if you want to loop thruogh the data do like this this example shows.inserting values in to the table..i hope this will help you
    – zabusa May 16 '15 at 14:11