How to convert scala list to javascript array? - javascript

Is there a simpler way of doing this?
$(document).ready(function () {
var jsArray = []
#if(scalaList != null) {
#for(id <- scalaList) {
jsArray.push('#id');
}
}
...
}

It's as simple as the following:
import play.api.libs.json.Json
val jsArr: JsValue = Json.toJson(scalaList)
You can also do that within a template:
#(list: List[Any])
#import play.api.libs.json.Json
<script type="text/javascript">
$(document).ready(function () {
var jsArr = #Json.toJson(list);
console.log(jsArr);
});
</script>

You can use mkString for this.
$(document).ready(function () {
var jsArray = #if(scalaList != null) {
[ #scalaList.mkString(",") ]}
else {[]};
}
You should omit this if statement in view. Instead of this, check null in controller and put empty list to view, so this code can be more simpler in view
$(document).ready(function () {
var jsArray = [ #scalaList.mkString(",") ];
}
You don't need this quotes ' ' around id. In javascript 1 == '1' is true

Have you tried something like:
var jsArray = new Array(#scalaList.map(x => "\"" + x + "\"").mkString(","));
or you can use a literal like
var jaArray = [ var jsArray = [#scalaList.map(x => "\"" + x + "\"").mkString(",")];
Also the if check is not required. For comprehensions are smart like that
$(document).ready(function () {
var jsArray = [#scalaList.map(x => "\"" + x + "\"").mkString(",")];
...
}

I think every answer are good but still not safe because every answers don't care about value which including ' or ". Fortunately play framework support json, so you should use json to convert to javascript array.
#(json: String)
<html>
<head>
</head>
<body>
<script>
var json = #Html(json);
var list = json.list;
</script>
</body>
</html>
package controllers
import play.api._
import play.api.libs.json._
import play.api.mvc._
object Application extends Controller {
def index = Action {
val list = List( "hoge\"hoge", "moge'mo\"ge" )
val json = Json.stringify( Json.obj(
"list" -> JsArray( list.map( JsString(_) ) )
))
Ok(views.html.index(json))
}
}

Related

Cannot get DOT NET CORE MVC to return multiple LINQ results to a view

I am able to pass one value from the controller method, see first cal query to return just the calorie value from the SQL LINQ query. However, I cannot get two colums, see my code controller code and javascript in the view below (I cannot work out what is causing zero data to be populated
I can see var mytext in javascript code return : {"foodCal":101,"foodVarient":"Vegan"}
public JsonResult GetCalories(string Productdata)
{
//THis is the orginal code which returns one value, CALORIES
//var calquery = (from c in _context.Foods
// where c.FoodName == Productdata
// select c.FoodCal).FirstOrDefault();
var calquery = (from c in _context.Foods
where c.FoodName == Productdata
select new
{ c.FoodCal, c.FoodVarient }
).FirstOrDefault();
if (calquery != null)
{
return Json(calquery);
}
else
{
calquery = null;
return Json(calquery);
}
}
<script src="/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
document.getElementById("FoodType").onchange = function ()
{
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetCalories")',
data: { Productdata: document.getElementById("FoodType").value },
success: function (data)
{
var mytext = JSON.stringify(data);
alert(mytext);
var obj = JSON.parse(json);
document.getElementById("FoodCalories").value = obj.foodCal;
document.getElementById("FoodHealth").value = obj.foodVarient;
}
});
}
});
</script>
I figured out the problem
var object =JSON.parse(mytext), not json
problem solved.
Hope other people benefit from this code.

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

How to correctly combine javascript with razor syntax

I have the following code in my razor view, I need to set some javascript variables to set the value coming from razor.
However the values of the variables are not being set.
var listPuntos =[];
function onSelect(e) {
var dataItem = this.dataSource.view()[e.item.index()];
#{
var proveedorID = 0;
<text>proveedorID = dataItem.ProveedorID</text>
var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID);
proveedorID = 0;
<text>listPuntos = list; </text>;
<text>
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
</text>
}
}
Given your concrete example, I would start by reducing the number of <text> blocks needed by instead just wrapping the shorter C# bits with #{ … }. This improves readability & lessens confusion. For example:
var listPuntos =[];
function onSelect(e) {
var dataItem = this.dataSource.view()[e.item.index()];
#{ var proveedorID = 0; }
proveedorID = dataItem.ProveedorID;
#{ var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID); }
proveedorID = 0;
listPuntos = #Json.Encode(list);
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
}
Next, to inject a C# value into JavaScript code being emitted by the server, you need to encode the value in JavaScript. The best way to do this is to convert it into JSON. This is done above using Json.Encode. In particular, the line reading:
listPuntos = #Json.Encode(list);
I've used Json.Encode but of course you are free to use whatever JSON library du jour that fits your project.
you should separate html code and javascript code.
First at all, don't call any server code from View when View is loading. Push all necessary arrays etc via model property in appropriate format (i.e. in json format) and then fill any client list from value of that property.
Secondly - move code like it :
var displayText;
$.each(listPuntos, function (key, value) {
if (displayText == undefined)
displayText = value.Nombre + ', ';
else
displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);
to appropriate section, like it:
#section scripts
{
<script>
.....
</script>
}

assigning a item from a .json file to a variable in javascript

I have a data1.json file
[
{
"BID" : "4569749",
},
{
"BID" : "466759",
},
{
"BID" : "4561149",
},
]
I want to call this .json file inside another abdv.js file and assign the BIDs to a variable array
var R1;
i.e the value of R1 = ['4569749', '466759', '4561149']
How can i do this??
.html file(please note: I am specifying only those parts relevant to this quetsion and erased other parts)
Code follows:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="abdv.js"></script>
<script>
loadABCD();
</script>
abvd.js
Code follows:
function loadABCD()
{
var R1 = [];
$.get('data1.json', function (data) {
var parsedArr = JSON.parse(data),
i = 0, l = parsedArr.length;
for (i; i < l; i++) {
R1.push(parsedArr[i].BID);
}
});
for(k=0;k<R1.length;k++)
{
document.write(R1);
}
// i will use R1 for later processing another function
// for(k=0; k<R1.length; k++)
// {
// obj = loadLevel4Obj(R1[k]);
// scene.add(obj);
// }
}
I also need help to read .json file into a javascript JSON object. I doubt whether the format of my json file is correct. Do i need to specify any other jquery related libs in the html file?? How do i check whether the BIDs are correctly stored in the variable R1.
Assuming you've read your json file into a javascript JSON object (do you need help with that as well?)
var R1 = new Array();
for(var i= 0 ; i< myJSON.length; i++){
R1.push(myJSON[i].BID);
}
[EDIT]
Your document.write is happening before you've done any reading.
Remove it.
put a console.log instead in your anonymous callback from your $.get();
Make it look like this:
$.get('data1.json', function (data) {
var parsedArr = JSON.parse(data),
for (i = 0; i < parsedArr.length; i++) {
R1.push(parsedArr[i].BID);
}
for(i=0; i< R1.length; i++)
console.log("item " + i + " = " + R1[i]);
});
Also if your json file really looks like this:
[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ]
Then it needs to be fixed to remove the extraneous commas inside your objects. It should look like this:
[ { "BID" : "4569749" }, { "BID" : "466759" }, { "BID" : "4561149" } ]
I haven't tested this, but it looks like it should work to me.
var R1 = [];
$.get('file.json', function (data) {
var parsedArr = JSON.parse(data),
i = 0, l = parsedArr.length;
for (i; i < l; i++) {
R1.push(parsedArr[i].BID);
}
});
Getting the json file with ajax, then process it and assign to R1:
function ajaxGetJson(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(eval(xmlhttp.responseText));
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
var R1;
ajaxGetJson('file.json', function(obj){
R1 = obj.map(function(item){ return item.BID });
});
Some comments:
I'm using eval instead of JSON.parse because your .json may not be in strict json format (as your example)
As the question has tag html5, your browser for sure supports the .map method
Cheers, from La Paz, Bolivia

Using Javascript with php

I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Categories

Resources