Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an alert in ejs file in nodejs

I would like to access a document object and want to use an alert for example.

So I've created a function in the ejs file and I want to show an alert when I have an error. So I am rendering my ejs file and give 2 params, one is the result and the other one is an error. and want to show if there is an error, show an alert.

 res.render('appandfeature',{data: apps, error:error});

and my ejs file

<% if(error!=null) 
showAlert(error.message);

%>  

showAlert = function(err) {

  alert('error: ' + err);
}
%>

As can be seen, I am calling alert and I have an error that is 'alert is not defined'.

I know it is server-side stuff. The question is how can I call an alert in ejs? I do not want to do something from ajax. If I can solve this problem in ejs, it would be great.

like image 676
ertan2002 Avatar asked Oct 27 '25 06:10

ertan2002


1 Answers

you can access EJS variable inside script tag :

<script type="text/javascript">
var error = <%= error %>;          

if(error!=null) 
{  
  showAlert(error.message);
}


showAlert = function(err) {
  alert('error: ' + err);
}
</script>
like image 135
Saurabh Mistry Avatar answered Oct 28 '25 20:10

Saurabh Mistry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!