I am trying to implement a new way for users to enter data into an HTML form with Slim Select JS library.
I have basic functionality working, with a pre-populated list of <option> items.
Originally, the PHP code would grab the list of names from a database (now in MongoDB), which is then looped through when the <select> element is created.
With Slim Select, you can pass in a "data array" as a parameter of the JS script. The manually-created format is this:
var jsPlayers2 = [
{"placeholder": true, "text": "Type Name"},
{"text": "Ernie Els", "value": "abc1"},
{"text": "Rory McIlroy", "value": "abc2"},
{"text": "Tiger Woods", "value": "abc3"}
];
new SlimSelect({
select: '#slim-select',
data: jsPlayers2, // THIS WOULD BE REPOINTED TO THE JSPLAYERS ARRAY VAR...
onChange: (info) => {
console.log(info)
}
})
My MongoDB document structure returned currently is:
var jsPlayers = [{
"_id": {
"$oid": "62b49410e63c2f8469089189"
},
"name": "Tiger Woods",
"clubs": [{
"clubId": {
"$oid": "6076030465508936f00e086c"
},
"name": "Jupiter FL",
"nickName": "Jupiter",
"logoPath": "jupiter.png"
}]
}, {
"_id": {
"$oid": "609d0993906429612483cfb1"
},
"name": "Ernie Els",
"clubs": [{
"clubId": {
"$oid": "6076030465508936f00e086c"
},
"name": "Wentworth UK",
"nickName": "Wentworth",
"logoPath": "wentworth.png"
}]
}, ...
}];
I have used a simplistic echo of this variable into a new JS variable:
var jsPlayers = <?php echo json_encode($players); ?>;
How can I only pick out the fields I need from within each document? Or is there a way to filter the array elements when I add them to the slim-select.data property?
You need to loop through your players to create the array you want to output as JSON. Something like this:
$options = [];
foreach ($players as $player) {
$options[] = (object)["text" => $player->name,
"value" => $player->getId()];
}
echo json_encode($options);
This only outputs the JSON.
Note that I used $player->getId(), which might not work for you. If your players are really objects you might have defined a method yourself to get their id.
Related
I have JSON file with this structure:
{
"launches": [{
"name": "First Name"
}],
"launches": [{
"name": "Second Name"
}],
"launches": [{
"name": "Third Name"
}],
"launches": [{
"name": "Fourth Name"
}]
}
I add the data like this:
$('#div-name').append(d.name);
When this is displayed on a webpage, it is placed in one div with no spaces. I can add a <p> tag to the append, but that still displays ALL the data and creates new divs to display it.
Basically, what I am trying to do is to create a div for each separate "name" value and display only one value per div.
First of all, your "json" is not a valid json, remmeber that in a json object, you can not have duplicated keys. You can easily use an online validator to help you with that... and after you fix it, let's assume that what you actually have is an array of objects like:
[
{"name": "Falcon 9"},
{"name": "Orion"},
{"name": "PSLV"},
{"name": "Soyuz"}
]
with this valid json, you can easily loop trough all the elements like (and take that you are using jQuery):
var json = [ ... ];
$(function() {
$.each(json, function(i, item){
$("p").append("<div>" + item.name + "</div>");
});
});
here's a live test: https://jsbin.com/bixadegeye/1/edit?html,css,js,output
A slightly different way of going about it:
var data = {
"names": [
"Falcon 9",
"Orion",
"PSLV",
"Soyuz"
]
};
$.each( data["names"], function( key, value ) {
$('#div-name').append(value+"<br />");
});
Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.
I'm using CakePHP to query my database table 'Task' that includes project_id, id, parent_id, title, description. My controller code handles the query like so:
$query= $this->Task->find('threaded', array(
'conditions' => array(
'Task.project_id' => 83,
),
'fields' => array(
'Task.id',
'Task.title',
'Task.parent_id',
)
));
//Pass the result to the view
$this->set('query', $query);
Then in my view, if I decode the json with the following:
<?php echo json_encode($simple); ?>
I get the following json structure:
[
{
"Task": {
"id": "475",
"title": "Have a Picnic",
"parent_id": "0"
},
"children": [
{
"Task": {
"id": "476",
"title": "Drive/Hike to Moutains",
"parent_id": "475"
},
"children": []
}
]
}
]
(I used this tool in to beautify it, the output is of course a continuous string)
But JS JIT SpaceTree requires the following structure:
{
"id": "aUniqueIdentifier",
"name": "usually a nodes name",
"data": [
{key:"some key", value: "some value"},
{key:"some other key", value: "some other value"}
],
children: [/* other nodes or empty */]
}
And I have no idea how to either adjust the output, or change my query to return the correct structure. Also, I've tried both 'threaded' and 'list' find() types and get the same structure. Any help is greatly appreiciated!
Simply iterate over the results and map the data into your desired structure, that's a pretty basic task. You could do that in the controller, in the view (maybe using a helper), or even in the model using a custom find method.
Here's a simple example. I don't know what data is good for, also there are no further fields in your result, so I've left that part.
function mapThreaded($source, &$target)
{
foreach($source as $item)
{
$node = array
(
'id' => $item['Task']['id'],
'name' => $item['Task']['title'],
'children' => array()
);
if(count($item['children']))
{
mapThreaded($item['children'], $node['children']);
}
$target[] = $node;
}
}
$tasks = $this->Task->find('threaded', array(...));
$tree = array();
mapThreaded($tasks, $tree);
pr($tree);
pr(json_encode($tree, JSON_PRETTY_PRINT)); // pretty print requires PHP >= 5.4.0
It should result in a JSON structure like this:
[
{
"id": "475",
"name": "Have a Picnic",
"children": [
{
"id": "476",
"name": "Drive/Hike to Moutains",
"children": [
]
}
]
}
]
In case Spacetree supports only a single root elment, simply use current($tree) or in JavaScript pass the first array entry to Spacetree.
I'm having trouble finding a solution that will help me loop through a bunch of elements and putting the chosen values into a table. I've been able to withdraw some values but the method isn't dynamic.
Here is an example:
var Table = {
"credit": {
"link": "site link",
"logoUrl": "logo url",
"message": "message"
},
"groups": [
{
"labels": [
{
"name": "Western Conference",
"type": "conference"
},
{
"name": "Central Division",
"type": "division"
}
],
"standings": [
{
"stats": [
{
"name": "gp",
"value": 20
},
{
"name": "w",
"value": 17
},
{
"name": "l",
"value": 0
},
{
"name": "gf",
"value": 64
},
{
"name": "ga",
"value": 37
},
{
"name": "gd",
"value": 27
},
{
"name": "pts",
"value": 37
}
],
"team": {
"id": 12345,
"link": "team link",
"name": "team name",
"shortName": "team"
}
},
This is the structure of the elements. So far I've used this:
document.getElementById("sGamesPlayed").innerHTML=Table.groups[0].standings[0].stats[0].value;
to withdraw values. However there are more teams, stats and divisions so I would need some kind of loop to go through the elements and put the into a dynamic table.
I would consider you to look at http://underscorejs.org/.
it provides a bunch of utility functions that could help you,
for example, _.each() helps you loop through JSON properties.
for the sample objects you've given (after completing the missing brackets at the end),
_.each(Table.groups[0].standings[0].stats, function(stats){
console.log(stats['name']+","+stats['value'])
})
gives me:
gp,20
w,17
l,0
gf,64
ga,37
gd,27
pts,37
how it works is that you provide the object you want as the first argument and the function that you give as the second argument will be called with each element of the first argument (Assuming it is a list).
I would also urge you to look at underscore templating that you can use to render your table where i put the console.log :
http://net.tutsplus.com/tutorials/javascript-ajax/getting-cozy-with-underscore-js/
http://scriptble.com/2011/01/28/underscore-js-templates/
I guess your question is about filtering the values of the array standings. In order to do that you can use the jQuery grep function (if you want to use jQuery).
For example you can write:
var arr = $.grep(Table.groups[0].standings[0].stats, function(d){return d.value>25})
Which will give
arr = [{"name": "gf","value": 64}, {"name": "ga", "value": 37},{"name": "gd", "value": 27},{"name": "pts", "value": 37}]
If this is not what you meant, can you please create a jsFiddle with a sample of what you want?
Depending on what you want to do with the results, you can go over the object using a scheme like:
var groups, standings, stats, value;
groups = Table.groups;
// Do stuff with groups
for (var i=0, iLen=groups.length; i<iLen; i++) {
standings = groups[i].standings;
// Do stuff with standings
for (var j=0, jLen=standings.length; j<jLen; j++) {
stats = standings[j];
// Do stuff with stats
for (var k=0, kLen=stats.length; k<kLen; k++) {
value = stats[k].value;
// Do stuff with value
}
}
}
Of course I have no idea what the data is for, what the overall structure is or how you want to present it. But if you have deeply nested data, all you can do is dig into it. You might be able to write a recursive function, but it might also become very difficult to maintain if the data structure is complex.
I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on