Can't get ejs value into script variable? - javascript

Whenever I attempt to set a variable within a script to be equal to an array rendered using ejs I get 'Invalid are unexpected token'.
Here is the snippet:
<script type="text/javascript">
var list = <%= events.slice(0) %>;
</script>
Originally I had it set to:
<script type="text/javascript">
var list = <%= events %>;
</script>
But I receive the same error. I was pretty certain you could render an ejs file that contains script tags and set the ejs variable to a variable within the script tag. Am I wrong?
Events is an array of event models for a calendar.

this is what you are looking for:
<script type="text/javascript">
var list = <%-JSON.stringify(events)%>;
</script>

You don't need to add script tags. Just put your code in html
Here is a plain example
index.ejs
<script>
//just call the events variable
for(var i = 0; i < events.length; i++){
var myEvent = events[i];
//handle the event
}
//then use the variables outside the script tag after you are done with all the handling
</script>
<ul>
<li><%=myDefinedVariable%></li>
<% var name = "Jake" %>
<li><%=name%></li>
<%for(var i = 0; i < 10; i++){%>
<li><%=name%></li> // puts li in the ul 10 times
<%}%>
</ul>

Related

How to move JavaScript code with Servlets into external file?

I have some JavaScript code with Servlets code, I want to move all of them (between ) to external js file, but it doesn't work, what can I do? How to modify my code if only part of JavaScript can move to external file.
<script language="JavaScript" type="text/JavaScript">
var sel = document.getElementById('sel');
var selList = [];
<%
String key = "";
String text = "";
for(int i = 0; i < master.size(); i++) {
Map option = (Map) master.get(i);
key = (String) option.get("Code");
text = key + " " + (String) option.get("NAME");
%>
selList.push({
key: "<%=key%>",
text: "<%=text%>"
});
<%
}
%>
</script>
Here two options:
1-by not using ajax
external.js
var images;
function renderImages(){
//do things for showing images here.
//images variable has images data as JSON (i suggest you this way) so you can easily iterate over list and render it.
}
jsp
<html>
<head>
<script type="text/javascript" src="external.js"></script>
<script>
images = "<%=request.getAttribute("imageDataAsJSON")%>"; //here i assume you populate request variable with your image data in JSON format. Be careful about parse errors due to ' and ".
</script>
</head>
<body>
<script>
renderImages();
</script>
</body>
</html>
2-by using ajax (you can seperate client side logic into external js code and populate data into it by doing ajax calls to server side.)
external.js
function renderImages(){
//do ajax to your servlet which returns image data as JSON.
//iterate over image data and render your html elements accordingly.
}
jsp
<html>
<head>
<script type="text/javascript" src="external.js"></script>
</head>
<body>
</body>
</html>

Scrape html with js

I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.

I can't get the session value to print

<script language="javascript" >
function addSelection(){
var tst="hello";
sessionStorage.setItem("test", tst);
<%
String pastst=request.getParameter("tst");
session.setAttribute("tst1",pastst);
%>
addSelection1();
}
function addSelection1(){
var outtst = '<%= session.getAttribute("tst1") %>';
<%
out.print("session"+session.getAttribute("tst1"));
%>
var tstout= session.getAttribute("tstout");
alert(tstout);
}
</script>
alert(tstout); works properly, but the code inside jsp prints blank.
I don't know what is the purpose behind this. Anyway few issues found in your code.
First. You cannot get the javascript variable value like this,
var tst="hello"; //Setting the value in javascript
sessionStorage.setItem("test", tst);
<%
String pastst=request.getParameter("tst"); //Expecting the value will be returned by java request
session.setAttribute("tst1",pastst);
%>
Second. Following line will provide you JS error, You cannot assign like this var tstout= session.getAttribute("tstout");
You need to change into, var tstout= '<% session.getAttribute("tstout"); %>'
Its wrong assumption javascript will print the session value in the following line,
<%
out.print("session"+session.getAttribute("tst1"));
%>
Finally, you need to start learning JSTL and EL avoid using scriptlets.
This is the way some where it is working.
<script type="text/javascript" >
function addSelection(){
var tst="hello";
sessionStorage.setItem("test", tst);
<%
String pastst="hello";
session.setAttribute("tst1",pastst);
%>
addSelection1();
}
function addSelection1(){
var outtst = '<%= session.getAttribute("tst1") %>';
alert('<%
out.print("session : "+session.getAttribute("tst1"));
%>');
alert(outtst);
}
</script>
Hope it helps you.

stuck with javascript-html output

I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>

Django/Ajax - Executing javascript in a template received through ajax call

In my application, I make an ajax call that renders this template with js:
<div id="ajax_reply">
<div id="hidden_data" style="display:none;"></div>
<script type="text/javascript">
var data = [];
data.push(['Col1', 'Col2', 'Col3', 'Col4']);
{% for entry in mydata %}
var dCell = [];
dCell.push({{ entry.Col1 }});
dCell.push({{ entry.Col2 }});
dCell.push({{ entry.Col3 }});
dCell.push({{ entry.Col4 }});
data.push(dCell);
{% endfor %}
document.getElementById('hidden_data').innerHTML = JSON.stringify(data);
</script>
</div>
This doesn't work, if I run the resulting js manually in console, it does get inserted into the div, but otherwise, the javascript is never executed. I've searched on SO but couldn't find questions on this exact topic. hidden_data is in scope, any suggestions?
EDIT:
Code seen in console after wrapping in onload (I had to make a few edits but running this manually in console works)
<div id="ajax_reply">
<div id="hidden_data" style="display:none;"></div>
<script type="text/javascript">
window.onload = function() {
var data = [];
data.push(['Col1', 'Col2', 'Col3', 'Col4']);
var dCell = [];
dCell.push('1233');
dCell.push('123312');
dCell.push('1233');
dCell.push('1482.61');
data.push(relation);
var dCell = [];
dCell.push('1231');
dCell.push('2112.0');
dCell.push('1231');
dCell.push('123123.00');
data.push(relation);
document.getElementById('hidden_data').innerHTML = JSON.stringify(relationsData);
};
</script>
</div>
If entry.Col1 contains string 'my text', resulting template will give you lines like this:
dCell.push(my text);
and, i suppose, you need
dCell.push('my text');
Make sure that this is executing after the DOM is loaded.
Try wrapping your script like:
window.onload=function(){
//script here
}
You can see on jsfiddle that this should be working.
Update:
It seems to be a problem with how Django is inserting data since it works with hardcoded sample data. Try the escapejs template filter to handle any potential javascript escaping problems. I've had to debug similar problems before with newlines and '&' symbols in particular.
dCell.push("{{ entry.Col1|escapejs }}");

Categories