I have jQuery token input implemented for tagging purposes where a user can search for a tag or create a new one thanks to railscasts ep#382 & ep#258. Data comes from the tags.json url which is the index action of the tags controller. The data from tags.json looks like so:
[
{
"created_at":"2013-06-21T16:30:19Z",
"explanation":"hitting the hosel of the club",
"id":8,
"name":"shank",
"updated_at":"2013-06-21T16:30:19Z",
"updated_by":"andy"
},
{
"created_at":"2013-06-22T17:40:37Z",
"explanation":"hitting the ground before the ball",
"id":12,
"name":"chunk",
"updated_at":"2013-06-22T17:40:37Z",
"updated_by":"andy"
}
]
My tags have a name as well as an explanation so I would like to include them in the results list like the Token and Results Formatting demo here http://loopj.com/jquery-tokeninput/demo.html#formatting.
The code below (number of entries omitted for brevity) is from the jQuery tokenInput Token and Results Formatting demo.
Instead of having "name": "Shank" manually entered here as well as the other omitted entries, how can I extract the name and explanation from tags.json hash and use them in the same was as the results formatter line, e.g. item.name & item.explanation?
tags.js
jQuery(function() {
var question = $('#question_tag_tokens')
return question.tokenInput([{
"name": "Shank",
"explanation": "hitting the hosel of the club"
}
], {
propertyToSearch: ["name"],
resultsFormatter: function(item){ return "<li>" + "<div class='tag' style='display:inline;color:#fff;'>" + item.name + "</div>" + " " + item.explanation + "</li>" },
prePopulate: question.data('preload')
});
});
The source for the example you referred to goes like this:
$(document).ready(function() {
$("#demo-input-local-custom-formatters").tokenInput(
[{
"first_name": "Arthur",
"last_name": "Godfrey",
"email": "arthur_godfrey#nccu.edu",
"url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
},
{
"first_name": "Adam",
"last_name": "Johnson",
"email": "wravo#yahoo.com",
"url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
},
...
],
{
propertyToSearch: "first_name",
resultsFormatter: function(item){ ... },
tokenFormatter: function(item) { ... }
});
});
tokenInput seems to take an array of objects. Once you load the json with ajax, you just pass it in and tell it what field to search on and some callbacks to format the results.
Related
I am trying to use the POST method to insert some data from a person with JSON. I am using the code from JS to construct, but when i start the transformation, it sends me "ERROR: invalid character ' ' in literal true (expecting 'e')". Does anyone know how to solve it?
const obj = {
"num_matricula": num_matricula,
"limit_date": "2022-05-20",
"admission_date": admission_date,
"cost_center": cost_center,
"pos_number": pos_number,
"role": role,
"department": department,
"pagamento": {
"vinculo": vinculo,
"valor": valor,
"recorrencia": recorrencia,
"contaBancaria": {
"banco": "001",
"carta": "c9160763-db6c-4e8c-a1ad-ad8709c99be2"
}
},
"deficiencia": deficiencia,
"jornada": jornada,
"profile": {
"name": name,
"email": email,
"mobile": mobile
},
"exame": {
"clinica": "6dc84ce4-7d9f-48ec-b9b1-a8a895a21fd4",
"data": "2022-05-15",
"hora": "14:00",
"obs": "Comparecer de manhã",
"guia": "e37dab24-c7a4-4b92-b9d1-32ed538b8300",
},
"docs": ["c9e26093-5e0c-4bd2-bea3-ac5182a6179f"],
"send_sms": true,
"send_email": true
};
const myJSON = JSON.stringify(obj);
Some columns are already provided with data from previous step (you can see in the images below), that is why i just repeated the column name in the JS code. Just to let you know, the boolean types of data are the columns: send_email, send_sms and deficiencia.
The problem is that JSON is a string. So in your first line you see this is not valid json: "num_matricula": num_matricula,
only numbers can be without double quotes: "num_matricula": 1234,
Using Datatables with a .json source file, I am trying to manipulate the data before it shows in the table. I'm trying to simply remove spaces and replace with a dash in this example.
There are two ways I understand to do some data manipulation. One is columnDefs the other is using dataSrc and return the data. Both fail when i try to utilize .split or .replace or even .toLowerCase()...
For example, I have columnDefs added like so:
columnDefs: [
{
"render": function ( data, type, row ) {
console.log(data);
var cn = data.split(" ").join("-").toLowerCase();
return cn;
},
"targets": 1
}
],
The console shows:
Uncaught TypeError: data.split is not a function
How do we manipulate the data with replace or the like?
My data looks like:
{
"Licensee": "Whistles for Woods",
"Contact Name": "Bob",
"Street": "2230 Trail",
"Suite / PO Box": 0,
"City": "Alturas",
"ST": "CA",
"Zip Code": 997733,
"Telephone": 0,
"Email Address": "bobc#email.com",
"Website Address": "www.domain.com",
"Fax": "No fax",
"Products": "whistle with custom logo",
"Categories": "Miscellaneous"
},
As discussed in the comments
We just want to make sure that we are indeed manipulating strings and not any other data type. So in this case we would change the code to look something like this:
columnDefs: [
{
"render": function ( data, type, row ) {
if(typeof data === 'string'){
//only if string manipulate
data = data.split(" ").join("-").toLowerCase();
}
// OR data = data.toString(); whichever is more convenient!
return data;
},
"targets": 1
}
],
I want to render mustache.js example. but I want to get data from external file.
I copy this data to "mydata.json" :
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}
I copy template to "template.html" :
{{#beatles}}
* {{name}}
{{/beatles}}
and render this files by this code :
$.get('template.html', function(template)
{
$.get('mydata.json',function(datas)
{
var rendered = Mustache.render(template, datas);
$('#content').html(rendered);
}
}
these codes not working until I remove function(s) from data file.
I tried : different 'dataType' in JQuery ajax request.
I tried : get data as text and then jQuery.parseJSON that data.
I tried : regular and LAMBDA syntax in functions scripts.
but I cant solve this problem.
I find the answer .
AJAX request datatype must be 'script' to receive data as json and function together.
So I'm having a problem accessing my json when its in a nested array. I previously had json set up like this with just one array and my .$each function worked perfectly. However I'm having trouble modifying it for this.
Json:
{
"tcontent": [{
"Name": "Septicaemia",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/septicaemia.jpg);'>",
"Variations": [{
"condition":"Community-acquired",
"organisms":"Staph. aureus",
"antimicrobial":"Flucloxacillin ",
"alternative":"(non anaphylaxis): ",
"comments": "Perform full septic screen."
}, {
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
}, {
"Condition":"Healthcare-associated",
"Organisms":"Varies",
"Antimicrobial":"Piperacillin",
"Alternative":"Seek advice from Consultant Microbiologist",
"Comments":"Always"
}]
}, {
"Name": "Infective Endocarditis (IE) (pending blood culture results)",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/endocarditis.jpg);'>"
}, {
"Name": "Central Nervous System Infections",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/cns.jpg);'>"
}, {
"Name": "Skin and Soft Tissue Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/skin.jpg);'>"
}, {
"Name": "Diabetic patients with foot infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/foot.jpg);'>"
}, {
"Name": "Bone and Joint Infections",
"url": "<a>",
"image":"<<div class='grid' style='background-image:url(img/anatomy/bone.jpg);'>"
}, {
"Name": "Intravascular Line Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/intravascular.jpg);'>"
}, {
"Name": "Urinary Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/urinary.jpg);'>"
}, {
"Name": "Respiratory Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/respiratory.jpg);'>"
}, {
"Name": "Gastrointestinal Infections",
"url": "<a>",
"image":"<div class='grid' style='backgroundimage:url(img/anatomy/gastrointestinal.jpg);'>"
}]
}
Here's my javascript to access it.
$(function (){
var imp = "Json/therapy.json"
$.getJSON(imp, function(data) {
var info = "<br>";
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
info += subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments
});
$(info).appendTo(".menu");
//alert(item)
};
});
});
});
I've tried a many variations on the var search but nothing seems to be working. I researched a lot of similar problems to this and I've been stuck on this for too long. Any light that can be shed on the situation would be much appreciated!
2 reasons why it doesn't work.
First of all javascript is case sensitive, Your variations differ.
subitem.condition fails on :
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
So change "Condition" to "condition", etc.etc.
second reason is the
Change $(info).appendTo(".menu"); to $(".menu").append(info);
Why?
$(".menu").append(info) Will just paste the string in the selected DOM element.
But you use
$(info)... and jquery does all kinds of fancy stuff now.
It tries to either use it as DOM selector, or create a new element.
Because your info starts with <br> $(info) tries to create a DOM element and it removes all text. Leaving just <br> because br cannot contain content.
Try to remove the initial <br> then you will see following error:
Uncaught Error: Syntax error, unrecognized expression:Community-acquiredStaph. aureusFlucloxacillin...
For example if you would type $("hahaha") , Jquery will try to find the tag <hahaha>, So when you remove the <br> your $(info) is looking for the tag <Community-acquiredStaph. aureusFlucloxacillin...>.
But because your string would then contain weird characters like "-()." It will fail. Hence the above error.
So you can only add html like this:
$("<span>hahah</span>").appendTo($(".menu"));
Or use selector
$("#myDiv").appendTo($(".menu"));
An example when $(info).appendTo(".menu"); working is:
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
var info = "<p>" + subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments + "</p>";
$(info).appendTo(".menu");
});
}
});
Using the following json:
http://pastebin.com/Bzpix1ai
I need your help with the json structure !! (I know it's easy but I cann't figure what the error is).
in this code I'm having a json file that contains a list of items (say restaurants) along with some details for each branch, like the address. In my js file I'm trying to print all the addresses that match specific item id.
I will post a sample of the json file and the js code to access it.
here is the json file:
{
"items" :
[
{
"item_id" :"204","details" :[{"country":"usa","city":"NY", "address":"bla bla bla"},{"country":"usa","city":"NY", "address":"another bla bla bla for the same id"}]
},
{
"item_id" :"234","details" :[{"country":"usa","city":"NY", "address":"another bla bla bla"}]
}
]
}
and here is the js code to access that file:
.....
success:function(data){
$.each(data.items, function(i,item){
if (item.item_id == 204 ) {
$("#results").append("<hr/>");
$("#results").append("<span class='result' >" + item.details.address + "</span><br/>");
}
});
}, ....
but it doesn't print any thing.
What do you think?
You don't actually need to use $.each in this case, because you have an array of objects i.e. [{}, {}, {}] is an array of objects, even though you actually have an object of arrays of objects :p. Each object has a specified index i.e. "item" whereas each array of objects has a default index of 0,1,2 etc.
Also yeah, because you have an array of address object details, you need to access them via details[0] or details[1]
Check this example out on jsFiddle
for(var i =0;i<data.items.length;i++) {
if (data.items[i].item_id == "204" ) {
$("#results").append("<hr/>");
$("#results").append("<span class='result' >" + data.items[i].details[0].address + "</span><br/>");
}
}
Your JSON is valid, so that is not the problem.
{
"items": [
{
"item_id": "204",
"details": [
{
"country": "usa",
"city": "NY",
"address": "bla bla bla"
},
{
"country": "usa",
"city": "NY",
"address": "another bla bla bla for the same id"
}
]
},
{
"item_id": "234",
"details": [
{
"country": "usa",
"city": "NY",
"address": "another bla bla bla"
}
]
}
]
}
You can view a modified example at: http://jsfiddle.net/wKDUu/. The code below will loop through the details to accomodate a more dynamic approach.
success:function(data){
var di = data.items;
for(var i=0;i<di.length;i++){
var ii = di[i];
if (ii.item_id == 204 ) {
$("#results").append("<hr/>");
for(var a=0;a<ii.details.length;a++){
$("#results").append("<span class='result' >" + ii.details[a].address + "</span><br/>");
}
}
}
}),
Since item.details is an array, you need to get it via item.details[0].address