mo0206
mo0206

Reputation: 801

how to insert data to an HTML div

I have a script which renders a sql query object to the view page. I am trying to retrieve the firstname from that object and want to print it on the UI.

I have function which does

 res.render(
      'login',
      {"data": data}); 

the data has a row

 [{id:9, user_name:'abc', email:'[email protected]', password: '1234', firstname: 'monica', lastname:'than'}]

I am passing this to an .ejs file where I am getting the firstname 'monica' like below:

 <body> 
 <h1> Welcome! </h1><p id="pil"></p>  
 <br>
 <br>
 <br>       
    <h3>Search for Pilgrim </h3>  
 <script>
    var name = <%- data[0].firstname %>
    document.getElementById("pil").innerText=  <%- data[0].firstname %>;
</script>      
</body>   

the name is getting value monica - as observed from debugger console.enter image description here

But I dont get this printed on the UI anywhere.

Can someone please tell me what is going wrong over here??

Upvotes: 0

Views: 199

Answers (2)

Amit Singh
Amit Singh

Reputation: 2275

You should be using:

var name = "<%- data[0].firstname %>";
document.getElementById("pil").innerText=  name;

As there's only one element with id="pil"

I think the problem is with wrapping the code in the function, may be you should try this:

<body onload="myFunction()"> 

and js be like:

function myFunction() {
  var name = "<%- data[0].firstname %>";
  document.getElementById("pil").innerText=  name;  
}

Here's the working FIDDLE

Upvotes: 1

Nikz
Nikz

Reputation: 1406

Try this-

document.getElementById("pil").innerHTML=" <%- data[0].firstname %>";

Upvotes: 2

Related Questions