Set array values in javascript from JSTL code - javascript

I have a code that looks like this:
In AnalyzeUserClient.jsp:
<c:set var="arrayList"><%= (ArrayList<String>)request.getSession().getAttribute("arrayList") %></c:set>
var sessionId = [];
<c:forEach items=${arrayList} var="id">
sessionId.push("${id}"); // add them one at a time, assuming string values
</c:forEach>
However,this line:
sessionId.push("${id}");
does not seem to be passing the values into the array "sessionId" (I viewed the source code on browser).So the question is,what can I do to pass the values into the array?
EDIT:I just realised that there are some problems as JSTL is server-side and JavaScript is client-side.So is there a workaround on it?

Don't mix EL and scriptlets. In fact, forget about scriptlets completely:
var sessionId = [];
<c:forEach items="${sessionScope.arrayList}" var="id">
sessionId.push("${id}");
</c:forEach>
Note though that this will generate invalid JavaScript if one of the IDs happens to contain a double quote. So you'd better JavaScript-escape the IDs before, in your controller. And I would suggest a completely different approach: serialize the list of IDs to a JSON string in your controller, and store this JSON string in request attribute. The JSP page will just need
var sessionId = ${jsonEncodedSessionIds};
which will translate to the following generated code:
var sessionId = ["id1", "id2"];

Related

How to send results from bash script (JSON format) into Javascript array variable (html file)?

My goal is to create simple search filter by name in html/javascript for data that I am getting from API in JSON format. In bash script I already formatted data so it is in right format for me to filter it later in javascript:
Data ready to be pushed/imported into let jsonData array (inside html file) from data file (example.json):
{"name":"vnode","address":"10.19.110.51","group":"windows","responsible":"Alen"},
{"name":"vnode2.izum.pri","address":"10.1.30.100","group":"windows","responsible":"Mario"},
{"name":"vnode3","address":"10.19.110.52","group":"windows","responsible":"John"}
I want to send this data from example.json and insert it into jsonData array inside javascript (index.html), How do I do it?
This is inside index.html:
<script>
let jsonData = `[
**DATA GOES HERE**
]`
function search_server() {
let input = document.getElementById("myInput").value;
input = input.toLowerCase();
let x = document.querySelector("#myUL");
x.innerHTML = "1";
for (i = 0; i < data.length; i++) {
let obj = data[i];
if (obj.name.toLowerCase().includes(input)) {
const elem = document.createElement("li");
elem.innerHTML = `${obj.name} , ${obj.address} , ${obj.group} , ${obj.responsible}`;
x.appendChild(elem);
}
}
}
</script>
I managed somehow to insert results from bash to html, but I only managed to do it into div class:
Method for sending bash results from file into div class element:
reg='<div class="content-middle">'
while IFS= read -r line; do
printf '%s\n' "$line"
[[ $line =~ $reg ]] && cat /usr/share/inventory/data.txt
done < /usr/share/inventory/indextemplate.html > /usr/share/inventory/index.html
So here is where I managed to send data:
<div class="content-middle">
</div>
No success on trying it to send into javascript:
reg='let jsonData = `['
while IFS= read -r line; do
printf '%s\n' "$line"
[[ $line =~ $reg ]] && cat /usr/share/inventory/data.txt
done < /usr/share/inventory/indextemplate.html > /usr/share/inventory/index.html
I don't have much knowledge on BASH but I think I have a solution.
First use BASH script to write a JS file, then place file in your project folder.
Insert your JS code in the empty JS file with BASH.
Use BASH to read your data file (example.json) to put the data in your JS file.
Good luck
I was able to do it with command AWK:
I created string to replace, in my example ****
Then i read file example.json, replace **** with content from example.json into new file bakka.html
With command:
awk 'FNR==NR{s=s"\n"$0;next;} /[*][*][*][*]/{$0=substr(s,2);} 1' '/usr/share/inventory/example.json' '/usr/share/inventory/index.html' > '/usr/share/inventory/bakka.html'
Thank you
Lawrence Cherone
If I have understood correctly, you have retrieved and parsed the data required into JSON-formatted objects saved in a file named example.json, and you now wish to assign the data to a variable within your html page so that it may be read and used by javascript in the page. (I will proceed on that basis so apologies if I have misunderstood).
The easiest way to make the data available is to include it in an expression, which will assign it to a named variable, at the time the file was written and to include the file by naming it with a .js, extension and reference it in a script tag from within the html (before the script that will make use of it).
First however, you will have to slightly modify the format of the JSON. Currently, your JSON data is arranged as three object notations, separated by commas:
current data format (in example.JSON):
{ -- 1st -- },
{ -- 2st -- },
{ -- 3st -- },
Such a structure has no meaning in javascript. If you examine JSON fetched with a typical api, it will usually list the object structures as elements of an array. If you reformat that file when you build it, you can make it so it is ready to use:
suggested format for exmaple.js:
const JSONdat = `[{"name":"vnode","address":"10.19.110.51","group":"windows","responsible":"Alen"},
{"name":"vnode2.izum.pri","address":"10.1.30.100","group":"windows","responsible":"Mario"},
{"name":"vnode3","address":"10.19.110.52","group":"windows","responsible":"John"}]`
Note the use of back ticks to avoid conflict with quote marks, and the presence of square brackets enclosing the data list. Note also, the value of JSONdat is a string, not an array nor objects (this is the purpose of JSON, to transport data as strings)
Next, in the html, load the file as a regular script (can be in the header, must be before the data is used):
html:
<script src="example.js"></script>
The JSON string is now available to JS in your document by referencing the name you gave it (JSONdat in the example above). The variable JSONdat has global scope and is available to javascript of any scope that loads later in the document.
To be able to iterate the array and read the object data, the JSON string has to first be parsed to make it an actual javascript array of objects:
const objectArray=JSON.parse(JSONdat)
objectArray now contains valid javascript objects inside a valid javascript array, which can be iterated as you wish to use the object data.
Working example:
const JSONdat = `[{"name":"vnode","address":"10.19.110.51","group":"windows","responsible":"Alen"},
{"name":"vnode2.izum.pri","address":"10.1.30.100","group":"windows","responsible":"Mario"},
{"name":"vnode3","address":"10.19.110.52","group":"windows","responsible":"John"}]`
// that variable will be available if the file holding it was loaded as a the src attribute of a regular script element.
const objectArray = JSON.parse(JSONdat);
console.log(objectArray[1].address);
// reports the value associated with the address key in the second object;

Javascript in HAML in Javascript

I've got a question that mightve been asked before but i have trouble finding a proper description. I hope someone can help me out.
In the code below on the line where i set var price i want to add the javascript variable accu_id to find a record in my DB through rails. How do I do this in embedded rails in javascript?
:javascript
$('#accu').change(function() {
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = "#{currency(Product.find_by(id: accu_id).price2)}"
$('#price_accu').append(price)
});
Or is there an easier way to do this?
You have two options.
You can use AJAX request to get data from database
You can use mapping concept like following
var data = #processed_data // json data, which contains processed data in json format.
var accu_id = $("#accu")[0].selectedOptions[0].value
var price = data.accu_id;
Here the #processed_data contains data like following
#processed_data = currency_calculation
def currency_calculation
Product.all.map { |product| [product.id, currency(product.price2) ] }.as_json
end
Example
Assume products table have two entries then the #processed_data contain values like following
{ "1" => "20.00", "2" => "25.50" }
The above data directly assigned to js variable data and accessed like data.key
The first option is best choice and second is possible one.
Note : You can't use js variable inside ruby.

jQuery parsing html into JSON

I am currently using the following code:
jQuery('#book-a-service').click(function(){
var selectedServices = jQuery('.selected').parent().parent().html();
console.log(selectedServices);
});
and that returns:
<td rowspan="3">Brakes</td>
<td class="service-title">BRAKES SET</td>
<td class="service-description"><p>Setting of front and rear brakes for proper functioning (excluding bleeding)</p></td>
<td class="service-price">R <span id="price-brakes-set">R75</span><div id="select-brakes-set" class="select-service selected"></div>
</td>
which is what i want, except i need an array of all the elements with '.selected' class in JSON.. i just want to know how i could almost parse it in a way that i only get the contents of the td tags and as for the "service-price" only the numeric value and then how would i insert those values into a json object?
Any Help Greatly Appreciated..
jQuery is not my most formidable frameworks, but this seems to do the trick.
jQuery('#book-a-service').click(function(){
var selected = jQuery('.selected');
selected.each( function() {
var children = jQuery(this).parent().parent().find('td');
var json = {};
console.log(children);
json.type = jQuery(children[0]).text();
json.title = jQuery(children[1]).text();
json.description = jQuery(children[2]).find('p').text();
json.price = jQuery(children[3]).find('span#price-brakes-set').text();
console.log(json);
console.log(JSON.stringify(json));
});
});
in action: http://jsfiddle.net/3n1gm4/DmYbb/
When various elements share the same class and you select them with $(".class"), you can iterate through all of them using:
$(".selected").each(function() {
var element = $(this); // This is the object with class "selected" being used in this iteration
var absoluteParent = $(this).parent().parent();
// Do whatever you want...
var title_element = $(".service-title", absoluteParent); // Get service-title class elements in the context provided by "absoluteParent", I mean, "inside" of absoluteParent
var title = title_element.html();
});
In the specific case of prices, I don't know exactly what is the price (probably R75?). Anyway, it should be inside a div and then select that div to obtain the price. If it is R75, then note that the "id" property should be unique for every DOM object in your HTML.
Also note that, when getting HTML, you're only getting a string, not the actual element, so it will probably not be useful for getting new values in an easy way (you won't be able to navigate through DOM elements with an ordinary string, even if it represents HTML from an actual object). Always get jQuery objects and work with them, unless you actually need the HTML.
For generating a JSON string, just create a global array and add the objects/values you need there. Then you can obtain a JSON string using var jsonText = JSON.stringify(your_array);
Consider not doing this in Javascript, as it's not useful in the majority of cases. Just send the values through POST value to a script (PHP, for example) and in the PHP you will get the actual value. The other way (PHP to Javascript) will be useful to return JSON (using json_encode($a_php_array)) and then, in Javascript, transform to a JS array using var my_array = JSON.parse(the_string_returned_by_php);.

convert string to dynamic array with variables in javascript

How would I take a string (that I got from a page using jQuery's text()) such as:
var myData = "[{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}]"; //this is a string :(
And turn it into the actual javascript object that I need, so for example:
var myObject = [{name:'xxx',data:[1,2,3,4,5]},{name:'yyy',data:[5,4,3,2,1]}];
So 'name' and 'data' will be non-dynamic variables, however names value, the data array and the length of myObject will be dynamic.
Not really sure where to start with this one. I am guessing that I will have to do a whole lot of spliting and looping, but I am open to suggestions.
Well, it can be done very easily:
var myObject = eval(myData);
However, you should be aware of the risks of the eval function. As it runs the value as a Javascript expression, it would also run any harmful code that would be in the string, so you should only use it when you have full control over what's in the string.
If you could change the format to be JSON, you could safely parse it without risks of code injection:
var myData = '[{"name":"xxx","data":[1,2,3,4,5]},{"name":"yyy","data":[5,4,3,2,1]}]';
var myObject = $.parseJSON(myData);
You mean,
var myObject = eval('(' + myData + ')');
?
EDIT
Its major con is that you can put any javascript code (not only JSON) to eval (Chrome's F12 lets anyone to exploit this). AS you are using jQuery, best choice will be
var myObject = $.parseJSON(myData);
for cross browser compatibility.
$.parseJSON
Takes a well-formed JSON string and returns the resulting JavaScript
object. Passing in a malformed JSON string may result in an exception
being thrown. For example, the following are all malformed JSON
strings:
{test: 1} (test does not have double quotes around it).
{'test': 1} ('test' is using single quotes instead of double quotes).

How to retrieve value from object in JavaScript

Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.

Categories

Resources