Unable to access array of entities passed through twig in javascript - javascript

I am currently working on a symfony2.0 project. At the moment I am stuck at some point where I want to use some simple javascript within my twig file.
From my controller I pass an array of entities called Machine to the twig file like this:
...
return $this->render('PRwissHostsBundle:mini:editLocation.html.twig',
array(
'form' => $form->createView(), 'id' => $id, 'machines' => $machinesInLoc,
));
My form inside the twig file easily cann acces the machines array. What I now need is to access this array within javascript.
Currently I m doing this like follwing:
<script type="text/javascript">
...
var mach_array = {{machines|json_encode|raw}};
var machine = mach_array[0];
alert(machine.name);
....
</script>
Somehow if I alert the mach_array it says that it is an object. Same result when I alert the machine. What is not possible is to access the machines id or name or whatevers property of it.
I have searched a couple of other questions like this but unfortunatly they were not helpfull regarding an array of entities.
Any help is highly appreciated.

In general, you shouldn't let Twig handle the data formatting unless it's absolutely necessary, for example as a response from a AJAX call.
With that said, your issue lies with how you declare the mach_array.
var mach_array = {{machines|json_encode|raw}};
should be
var mach_array = '{{machines|json_encode|raw}}';
By not wrapping the call to twig, Javascript will make mach_array a Object, its the same as
var mach_array = {"foo" : "bar"}
which resolves to a Object.

So I just solved my problem with the help of Nihilnovi. The problemw as not an empty array like gregory supposed, I just did not realy figure out how to properly use javascript and twig entities. The working code now looks like following:
<script type="text/javascript">
function report(period){
var e = document.getElementById("form_machines");
var selectValue = e.options[e.selectedIndex].value;
var selectText = e.options[e.selectedIndex].text;
if (selectValue != ""){
var table = document.getElementById("uebersicht");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<b>Name:</b>";
var mach_array = {{machinesAvailable|json_encode|raw}};
{% for machine in machinesAvailable %}
if ({{machine.name|json_encode|raw}} == selectText){
cell2.innerHTML = "<a href='{{ url('PRwissHostsBundle_det_machine', { 'id':machine.id }) }}'> {{machine.name}} </a>";
}
{% endfor %}
cell3.setAttribute('align', 'right');
cell3.innerHTML = "<input type='checkbox' id=machine.id >";
}
}
</script>
Hope this helps some who steps into the same issue!

Related

jinja2 - TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endfor' or 'else'

I wish to display the data retrieved from SQLite onto webpage. The display layout is a table. But I received below comments:
jinja2.exceptions.TemplateSyntaxError
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
I m new to coding and may I seek help from you? Many thanks.
Welcome {{username}}, your schedule is as follows.
<tbale id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
<script>
var staff;
for (var j=0; j < 1000: j++) {
staff = {
{% for key,user in df_dict.items()%}
department: "{{user.workingdept}}" + j,
staffid: "{{user.staffid}}" + j,
staffname: "{{user.staffname}}" + j,
rank: "{{user.rank}}" + j,
shift: "{{user.shift}}" + j,
{% endfor%}
};
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell1 = row.insertCell(2);
cell1.innerHTML = staff.department,
cell2.innerHTML = staff.staffid,
cell3.innerHTML = staff.staffname,
cell4.innerHTML = staff.rank,
cell5.innerHTML = staff.shift;
<br>
</body>
<html>
Jinja2 (Your backend templating engine) requires a space character between opening-/closing-indicator and your actual command.
The error is about the "endfor" command not being found. You can solve this problem by correcting your syntax in the following way:
{% endfor%} becomes {% endfor %}
Even though this answers your question, you will run into more errors with your code. A few examples of what should be fixed:
Your table opening tag is misspelled (tbale).
You are missing a few HTML tags for your page to be valid or have them wrongly placed.
You are defining "var cell1" (JavaScript) multiple times.

Cannot get the number of var using javascript

I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.

acts_as_votable javascript html table

I'm trying to use the acts_as_votable gem in ruby on rails. However, I get stuck when I need to add the button to the view.
I want to add a voting system to a list of item which are put into an html table as users fill out the form in the web browser.
I can insert a 'like' button in each row for each 'destination' item. However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?
Here is the dashboard.js:
var insertDest = function(dest) {
// Find a <table> element with id="myTable":
var table = document.getElementById("destTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var name_cell = row.insertCell(0);
var address_cell = row.insertCell(1);
// var delete_cell = row.insertCell(2);
var like_cell = row.insertCell(2);
like_cell.innerHTML = '<input class="Like" type="button" value="Like" />';
var like_count_cell = row.insertCell(3);
like_count_cell.innerHTML= 0;
// Add some text to the new cells:
name_cell.innerHTML = dest.name;
address_cell.innerHTML = dest.address;
// delete_cell.innerHTML = "<div class='del'>x</div>";
addMarker(dest.address,map);
};
var insertAllDest = function(trip){
var d = trip.destinations;
for (i in d){
insertDest(d[i]);
}
};
However, does this mean I need to write a 'attachLikeHandler' function
to deal with what happens when the like button is clicked?
Yes:
$(".like").on('click', function() {
$.ajax({
method: "PUT",
url: "/photos/" + $(this).attr("id"),
success: function(msg_from_server) {
alert(msg_from_server); //"Thanks for voting!" or "Sorry, you already voted!"
}
});
});
If you have a route declared as resources :photos, then a url like /photos/12 will send a request to photos#update, then inside the update action params[:id] will be 12. Note that you'll need to add the resource id to the html when constructing the html.

php vars are updating but javascript function shows allways first value

I have a php class that set values and updates them. I use getters methods to access those varibles from a javascript function and show them in screen. My problem is when I launch that javascript code, my vars are shown allways with the first values they get. I've checked them and they are up to date when I call myCreateFunction(); but is like this function launches before the php vars are updated. I'm new in javascript and some help would be appreciated, thanks!
<?php
class TableRows {
public $offerId = 0;
public function setOfferId(){
$this->offerId ++;
}
public function getOfferId(){
$this->offerId;
}
}
$tb = new TableRows();
?>
<script>
function myCreateFunction(string) {
var offerId = '<tr><th>'+<?php echo json_encode($tb->getOfferId()); ?>+'</th></tr>';
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = offerId;
}
</script>
<script>
myCreateFunction();
</script>
<?php
$tb->setOfferId();
?>
<script>
myCreateFunction()
</script>
Yes, because myCreateFunction is being rendered by your browser on your second call. PHP (server-side) has nothing in common with JavaScript (client-side). Don't mix your code like that.
Instead, you can use setters, getters, and then pass the value to your JavaScript function as parameter.
You have some problem in understanding where you are in your code (in javascript or in php). $tb->setOfferId(); does not modify anything in your javascript. So the second call to myCreateFunction() will be exactly the same.

Query String for pre-filling html form field

I manage a website for an organization that has separate chapter sites. There is a membership signup form that is on the main website that each chapter links to. On the form there is a dropdown box that allows a person to choose the chapter they want to join. What I would like to do is have each chapter website use a specific link to the form that will preselect their chapter from the dropdown box.
After searching the web, I found that I will probably need to use a Javascript function to utilize a Query String. With all my searching, I still can't figure out the exact code to use. The page is a basic HTML page...no php and it is hosted on a linux server.
Any help would be greatly appreciated.
If you format your url like this:
www.myorg.com?chapter=1
You could add this script to your html head:
function getparam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
function loadform()
{
var list = document.getElementById("mychapterdropdown");
var chapter = getparam("chapter");
if (chapter>=0 && chapter < list.options.length)
{
list.selectedIndex = chapter;
}
}
The in your html body tag:
<body onload="loadform();" >
Could probably add more validation checks but that's the general idea.
It sounds like what you are looking for are GET or POST requests. For instance, if your user selects "Chapter A" from your form and hits select, you can allow redirects from another site (for instance http://www.yoursite.com/form.html?chapter=A) to allow Chapter A to be preselected. In Javascript this is done by
var chapter="";
var queryString = location.search.substring(1);
if ( queryString.length > 0 ) {
var getdata = queryString.split("&");
var keyvalues;
for(var i=0; i < getdata.length; i++){
keyvalues = getdata.split("=");
}
} else {
chapter = "Not Found";
}
document.getElementById( "ChapterID").value = keyvalues['chapter'];
This is untested, so don't hold me to it :).
maybe something using parse_url
$params = parse_url()
$query = $params['query'];
$query_pairs = explode('&',$query);
$key_val = array();
foreach($query_pairs as $key => $val){
$key_val[$key] = $val;
}
http://www.php.net/manual/en/function.parse-url.php
You would probably have to use an dynamic ajax content. Use the following javascript to read the querystring, then load the html file in that div using this javascript.

Categories