I got stuck to rendered JSON data by an id, already browse over the several articles but not working.
I had ajax call:
$.ajax({
url: '../../../get/api/city.json',
dataType: 'json',
})
.done(function(data){
console.log(data);
var HTML = '';
$.each(data.city, function(i,city){
HTML += '<span>'+city.city_name+'</span>'; });
$('#title').append(HTML);
})
.fail(function(){
alert('failed');
});
And the json output is:
{"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]}
My situation I created a html page to render the information for City A, what I want is to filter the above JSON data only rendered the information from city A.
Big thanks for any help from you guys.
Thanks
Try the following using Array's filter():
var info = {"city":[
{"id":"4","year":"2014","city_name":"City A"},
{"id":"5","year":"2014","city_name":"City B"},
{"id":"6","year":"2014","city_name":"City C"}]};
var res = info.city.filter(function(item){
return item.city_name =='City A';
});
console.log(res);
var HTML = '<span>'+res[0].city_name+'</span>';
$('#title').append(HTML)
HTML = '<span>'+res[0].id+'</span>';
$('#id').append(HTML);;
HTML = '<span>'+res[0].year+'</span>';
$('#year').append(HTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="title">Title: </div>
<div id="id">Id: </div>
<div id="year">Year: </div>
UPDATE:
Once your request server send data, you can use the following code:
$.ajax({
url: 'http://207.254.40.122/deetab/json.json',
dataType: 'json',
crossDomain: true
}).done(function(data){
console.log(data);// Check here whether sever send data or not
var res = data.city.filter(function(item){
return item.city_name =='City A';
});
//console.log(res);
var HTML = '<span>'+res[0].city_name+'</span>';
$('#title').append(HTML)
HTML = '<span>'+res[0].id+'</span>';
$('#id').append(HTML);;
HTML = '<span>'+res[0].year+'</span>';
$('#year').append(HTML);
});
You could add a filter to your $.each to check if the city id is the one you want.
$.each(data.city, function (i, city) {
if (city.id === 4)
HTML += '<span>' + city.city_name + '</span>';
});
Can prepare a filter with your desired city name and apply it to your data array to filter data preferred by you as in example:
var cities = {
"city": [{
"id": "4",
"year": "2014",
"city_name": "City A"
}, {
"id": "5",
"year": "2014",
"city_name": "City B"
}, {
"id": "6",
"year": "2014",
"city_name": "City C"
}]
};
//Want only city with this name
var filter = "City A";
console.log(cities.city);
cities.city = cities.city.filter(function(obj) {
return obj.city_name == filter;
});
console.log(cities.city);
Related
I'm trying to append parts of a JSON array (that is received from a server) to a table after clicking a button. Somehow I can't add the parts of the json array to this table.
This is the JSON Array received from the server:
{"pass": [
{
"Date":"01.01.2001",
"Time":"14:20",
"ID":"1234",
"Name":"Sat",
"elevation":"168.9°",
"losTime":"04:31"
},
{
"Date":"01.01.2002",
"Time":"14:30",
"ID":"1235",
"Name":"Com",
"elevation":"16.9°",
"losTime":"04:25"
}
]}
The Code is the following:
$(document).ready(function(){
$("#submit-button").click(function() {
$.ajax({
url: "../rest/passdata",
type: "GET",
data: {
satellite: document.getElementById("satellite").value,
startDate: document.getElementById("startDate").value,
startTime: document.getElementById("startTime").value,
endDate: document.getElementById("endDate").value,
endTime: document.getElementById("endTime").value
},
dataType: "json",
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(response) {
var arr = response;
$("#pd-table").find("#pd-body").empty();
$.each(arr, function(i, value){
var checkbox = $('<input type="checkbox"/>');
$("#pd-table").find("#pd-body")
.append($("<tr>"))
.append($("<td>").append(checkbox))
.append($("<td>").append(arr.pass.ID[i]))
.append($("<td>").append(arr.pass.Date[i]))
.append($("<td>").append(arr.pass.Time[i]))
.append($("<td>").append(arr.pass.losTime[i]))
.append($("<td>").append(arr.pass.Name[i]))
.append($("<td>").append(arr.pass.elevation[i]))
.append($("</tr>"))
The checkbox gets added to the table, which makes me think that reading out the array does not work the way it should.
I already tried to parse the response from the server but that also didn't work out and in that case even the checkbox didn't get added to the table.
I hope someone can help me out!
Several problems:
You want to loop over the array in response.pass not the whole object
You are appending the cells to the <tbody> not to the new row.
You can not append a closing tag. The DOM only accepts complete elements and has no understanding of appending a closing tag in a jQuery object. The full element gets created when you do $('<tagname>')
Simplified version:
var arr = response.pass;
var $tbody = $("#pd-body").empty();
$.each(arr, function(i, value) {
var checkbox = $('<input type="checkbox"/>');
var $row = $("<tr>")
// append cells to the new row
.append($("<td>").append(checkbox))
.append($("<td>").text(value.ID))
.append($("<td>").text(value.Date))
.append($("<td>").text(value.Time))
.append($("<td>").text(value.losTime))
.append($("<td>").text(value.Name))
.append($("<td>").text(value.elevation));
// append complete row
$tbody.append($row)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="pd-table" border=1>
<tbody id="pd-body">
</tbody>
</table>
<script>
var response = {
"pass": [{
"Date": "01.01.2001",
"Time": "14:20",
"ID": "1234",
"Name": "Sat",
"elevation": "168.9°",
"losTime": "04:31"
},
{
"Date": "01.01.2002",
"Time": "14:30",
"ID": "1235",
"Name": "Com",
"elevation": "16.9°",
"losTime": "04:25"
}
]
}
</script>
Hi I need to convert the following json into a html table
{
"condomini": [
{
"ricevute": [
{
"data": "31/10/2017",
"numero": "1715759",
"dettagli": "Contante",
"descrizione": "Versamento giuseppe rossi rata ottobre ",
"totale": "108,00",
"righe": [
{
"importoPagato": "5,00",
"importoCredito": "5,00",
"importoResiduo": "0,00",
"scala": "B",
"piano": "2",
"interno": "12",
"descrizione": "Contributo per riparazione cancello A"
},
{
"importoPagato": "103,00",
"importoCredito": "103,00",
"importoResiduo": "0,00",
"scala": "B",
"piano": "2",
"interno": "12",
"descrizione": "Rata ottobre - dicembre 2017"
}
]
}
]
}
]
}
So far this is what I’ve managed to do, but i don’t know how to render the array “righe”, if you put the json code into http://json2table.com/ then you have an idea how the table should look like.
$.ajax({
type: "json",
url: "../km-client-controllers/km-ctrl-client-ricevute.php",
success: function(result) {
datas = JSON.parse(result);
$('#nome_condominio').html(datas.condomini[0].condominio.nome);
$('#indirizzo_condominio').html(datas.condomini[0].condominio.indirizzo);
$.each(datas.condomini[0].ricevute, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.data),
$('<td>').text(item.numero),
$('<td>').text(item.descrizione),
$('<td>').text(item.totale)
).appendTo('#records_table');
});
I am not sure how you want your table to look, but to get the data inside the righe array you can do
$.each(item.righe ....)
similar to how you getting the data from the ricevute array.
See this fiddle for an example: http://jsfiddle.net/zs0yowhk/21
I have a list of resources like the following html content loaded from the resources_data.json data I loaded to my app externally from the same server.
<div class="callout">
<div class="large-8 medium-8 small-8 columns left">Demo</div>
<div class="large-2 medium-2 small-2 columns right">
<a href="#" class="deleteResource" data-id="1" data-name="Demo">
<i class="fa fa-close red"></i> DELETE</a>
</div>
</div>
I would like to be able to delete items from this list by the "id" not having to match the "resourceName" so for every delete I will be deleting the entire object essentially I would not like to save the file back to the server to save time on the response but I am not sure if I can just delete a string of an external file without re-saving it.
MY JSON:
"calendarResources": [
{
"id": 1,
"resourceName": "Demo"
},
{
"id": "4",
"resourceName": "New Test Resource"
},
{
"id": "2",
"resourceName": "test"
},
{
"id": "5",
"resourceName": "another test"
},
{
"id": "6",
"resourceName": "new test data"
},
{
"id": "7",
"resourceName": "better one"
},
{
"id": "8",
"resourceName": "the one!"
},
{
"id": "12",
"resourceName": "Dune one"
},
{
"id": "13",
"resourceName": "res test"
}
]
I am trying to use the delete function to delete the string and upload the data back to the json again but something is going wrong here that nothing works and I get the same data again.
MY JS:
function deletingResource() {
$("body").on("click", ".deleteResource", function (e) {
e.preventDefault();
var resourceId = $(this).data("id");
var resourceName = $(this).data("name");
$.getJSON(appDirLocation + "_data/resources_data.json", function (jsonData) {
console.log(jsonData);
var resourceDeletion = ({
"id": resourceId,
"resourceName": resourceName
});
delete jsonData.calendarResources[resourceDeletion]; // delete data string
var newJsonOutput = JSON.stringify(jsonData); //stringify new data to save
var jsonFile = new BCAPI.Models.FileSystem.File(appDirLocation + "_data/resources_data.json");
jsonFile.upload(newJsonOutput).done(function () {
$("#resourcesList").html("");
console.log("RESOURCE DATA DELETED");
renderResources();
}).error(function (jqXHR) {
console.log("RESOURCES JSON FAILED DELETE: " + jqXHR.responseText);
}); // END OF JSON CREATING
console.log(newJsonOutput);
}).done(function () {
$(this).closest(".resourcesData").hide();
}).fail(function (jqXHR) {
console.log("Request failed." + "Error code: " + jqXHR.status + "Error text: " + jqXHR.statusText + "Response text: " + jqXHR.responseText);
});
});
} // DELETING RESOURCES
deletingResource();
Thanks for the help in advance...
Based on an answered question posted here also referencing the Array.prototype.filter() function I was able to resolve this with grace!
I Recommended for anybody looking to work with json files using javascript to check the Array property of the javascript library in MDN WEB DOCS
Code fixed:
jsonData.calendarResources = jsonData.calendarResources.filter(item => item.id != resourceId); // WORKING ######
var newJsonOutput = JSON.stringify(jsonData);
var jsonFile = new BCAPI.Models.FileSystem.File(appDirLocation + "_data/resources_data.json");
i have the following Problem. Sorry for my bad english that way.
I want to read a jsonfile and count the Number of Persons in it.
This result i will write to an variable.This variable is connected to the TileContainer. So when i write an new entry in my Json File i want that the TileContainer number is increased to.
Here my Code from my Company.json File:
{
"mitarbeiter": [
{ "Lastname": "Mustermann",
"Firstname": "Max",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "männlich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Softwareentwickler"
},
{ "Lastname": "Fischer",
"Firstname": "Elke",
"icon": "sap-icon://globe",
"adress": "Hamburg",
"geschlecht": "weiblich",
"plz": "31441",
"street": "Am Fischmarkt 12",
"jobinfo": "Verwaltungsassistentin"
},
{ "Lastname": "Mustermann",
"Firstname": "Heike",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "weiblich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Vorstandsvorsitzende"
}
]
}
on my controller.js
onInit: function() {
this.getView().addDelegate({onBeforeShow: function(evt) {
if (this.direction != "back") {
var model = new sap.ui.model.json.JSONModel();
model.loadData("JsonModels/Company.json");
alert(model.getJSON());
var XYZ;
var jsonModel =
{
"Tiles":[
{"Tile":
{ id : "idModelTile1",
title : "Mitarbeiter",
info: "Mitarbeiterdaten",
icon:"sap-icon://company-view",
activeIcon:"inbox",
number: XYZ,
appto: "idListPage"
//numberUnit: "positions"
},
}, ......
I want that the variable XYZ gets the Length Value, bevor the TileContainer is rendered. So the Number of Company-Employess is given on the Selectionscreen View.
Hope some one can help me. I make some implementations with jquery and so but nothing really work fine.
Dear,
Christian
When i add
alert(model.getProperty("/mitarbeiter/length"));
i get the alert message "undefined"...
Since the length property of an array can be read, you could simply use
var XYZ = model.getProperty("/mitarbeiter/length");
EDIT: here's a code example for the comment I gave below
onInit: function() {
jQuery.ajax({
url: "JsonModels/Company.json",
dataType: "json",
success: function(data, textStatus, jqXHR) {
var mitarbeiterCount = data.length;
var oTileModel = new sap.ui.model.json.JSONModel();
oTileModel.setData({
tiles :[{
tile : {
id : "idModelTile1",
title : "Mitarbeiter",
info : "Mitarbeiterdaten",
icon :"sap-icon://company-view",
activeIcon:"inbox",
number : mitarbeiterCount,
appto : "idListPage"
},
}]
});
sap.ui.getCore().setModel(oTileModel);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Oh no, an error occurred");
}
});
}
In your view, if you now bind your tile's number property, it should automagically work:
var oTileTemplate = new sap.m.StandardTile({
icon : "{icon}",
number : "{number}",
numberUnit: "mitarbeiter",
title : "{title}",
info : "{info}"
});
var oTileContainer = new sap.m.TileContainer().bindAggregation("tiles", "/", oTileTemplate);
//Etc...
Im currently requesting the Open Graph url through JSON like so:
https://graph.facebook.com/me/friends?fields=email,likes,name,birthday,location,website&access_token=$token
My JSON request is succesful, however my issue is to actually loop through the returned data, so that I can list it on my page.
I've tried with the following:
$('#goButton').click(function () {
//Call the JSON feed from the Open Social Graph.
$.getJSON("https://graph.facebook.com/me/friends?fields=email,likes,name,birthday,location,website&access_token=" + savedFbToken + "&callback=?",
//Once it is returned, do something with the JSON:
function (data) {
console.log(data);
//Clear out the placeholder
$('#Placeholder').html("");
//Add some new data
$('#Placeholder').append("<h1>Name:</h1>" + data.name + "");
$('#Placeholder').append("<span>Birthday: "+ data.birthday +"</span><br/>");
$('#Placeholder').append("<span>Location: "+ data.location +"</span><br/>");
$('#Placeholder').append("<span>Id: "+ data.id +"</span><br/><br/>");
});
});
The format returned looks like this:
{
"data": [
{
"name": "Name 1",
"birthday": "10/08/1983",
"location": {
"id": "110343502319180",
"name": "Copenhagen, Denmark"
},
"id": "263901486"
},
{
"name": "Name 2",
"birthday": "02/16/1982",
"location": {
"id": "110398488982884",
"name": "Reykjav\u00edk, Iceland"
},
"id": "502533736"
},
etc...
Any suggestions on how to loop through this correctly?
data actually contains an object with an array of objects also named data, so you would need to loop through that
$('#Placeholder').html("");
for( var i = 0; i < data.data.length; i++ ){
//Add some new data
$('#Placeholder').append("<br />");
$('#Placeholder').append("<h1>Name:</h1>" + data.data[i].name + "");
$('#Placeholder').append("<span>Birthday: "+ data.data[i].birthday +"</span><br/>");
$('#Placeholder').append("<span>Location: "+ data.data[i].location +"</span><br/>");
$('#Placeholder').append("<span>Id: "+ data.data[i].id +"</span><br/><br/>");
}