Reputation: 425
I have my files
object on back-end:
[{ Id: 3,
UserId: 7,
FileType: 'application/pdf',
FileContent:
<Buffer 25 50 44 46 2d 31 2e 33 0d 0a 25 e2 e3 cf d3 0d 0a 0d 0a 31 20 30 20 6f 62 6a 0d 0a 3c 3c 0d 0a 2f 54 79 70 65 20 2f 43 61 74 61 6c 6f 67 0d 0a 2f 4f ... >,
FileName: '1',
UserUploadId: 7 },
...]
I am sending this object to the view:
res.render('dashboard/files/index',{'title': 'My files', 'my_files' : files})
On HTML I am rendering with handlebarsjs
a table containing a row per file and a button that executes a function receiving as unique parameter the file Id
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">UserId</th>
<th scope="col">View</th>
</tr>
</thead>
<tbody>
{{#each my_files}}
<tr>
<td>{{this.UserId}}</td>
<td>
<button onclick="viewPdf({{this.Id}})"></button>
</td>
</tr>
{{/each}}
</tbody>
</table>
In the same document, with JavaScript, I am trying to get the FileContent
property of the object, but for this I need to find the file in the array my_files
searching by Id
parameter.
<script>
function viewPdf(Id){
var found_file = my_files.find(function(element) {
return element.Id == Id;
});
console.log(found_file)
}
</script>
But I am getting this error output:
Uncaught ReferenceError: my_files is not defined at viewPdf (......:465) at HTMLButtonElement.onclick
Upvotes: 1
Views: 785
Reputation: 258
So,
JavaScript running server and browser side is different. You can't find a declared server side variable in the browser, vice versa.
A way to shared variable between server and client :
function viewPdf(Id){
$.ajax('/getFiles', {
success:function(my_files){
// put logic here
}
})
}
Upvotes: 2