Using JSON Array with AJAX - javascript

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>

Related

How to convert json to html table

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

How to prevent my "push" from putting everything in one array?

I have input fields, which are created based on my arrays in my JSON file.
However, when I insert something in my input fields, it goes right until I start inserting stuff in the input fields that aren't part of the other input fields. Don't worry, more explaining to come.
This is how my JSON looks like:
{
"main_object": {
"id": "5",
"getExerciseTitle": "TestFor",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestFor",
"language": "nl_NL",
"exercises": [{
"word": "test",
"syllables": [
"test01",
"test02",
"test03",
""
]
},
{
"word": "tesst",
"syllables": [
"test11",
"test12",
"",
""
]
}
]
},
"dataType": "json"
}
}
As you can see I have multiple arrays called syllables. What I am trying to do is: Create the push until it reaches the matched array in JSON, it should then change the input fields to buttons. However, when I go over to the next input fields that are linked to the second array, instead of starting the push from 0 it keeps on going.
A picture for you to see what I mean (note the console.log() too).
So: Instead of having the push start over it keeps on adding it to the already existing array. I want this NOT to happen so I can later on make a check that checks whether the push equals the array and then assign all the desired input fields to green buttons.
This is how my code looks like right now:
var x = [];
function prepareCheck() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
$(document).on('change', '.syl-input', function() {
var rowCounter = $(this).parent().parent().parent().parent().attr('id');
var inputCounter = $(this).attr('id');
var jsyl = json.main_object.main_object.exercises[rowCounter].syllables[inputCounter];
var jsylall = json.main_object.main_object.exercises[rowCounter].syllables;
var valueInput = $(this).val();
console.log(jsylall);
if (valueInput == jsyl) {
var correctInput = $('<input/>', {
'class': 'form-control',
'type': 'text',
'id': 'button' + CBC++,
'value': valueInput
});
console.log(jsyl);
x.push(valueInput);
if (valueInput == '') {
x.remove($(this).val());
};
console.log(x);
$(this).replaceWith(correctInput);
S.playRight();
S.addRight();
} else if ($.inArray(valueInput, jsylall) >= -1) {
$(this).css({
'color': '#e00413'
});
S.playWrong();
S.addWrong();
}
});
});
}
Question: How can I reset x.push again? so I can keep on checking whether the input fields have the desired words/length to change them to green buttons?

Only show JSon by key value

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);

Fill dropdown list with json

I have SQLite table with columns id and name. I return array of those rows like json from autocomplete.php page. How to fill select with options ( drop down list ) with this json using jquery and JavaScript ? I am new to JavaScript and JQuery, I googled but didn't find how. In ASP.NET this is easy but here I don't know. Would somebody help ?
This is example of my JSON, can be much longer.
[
{
"id": "1",
"name": "test"
},
{
"id": "1",
"name": "test"
}
]
HTML:
<select id="sel">
</select>
JavaScript:
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
Here's a working example. http://jsfiddle.net/ms2Ma/
Try this, This will give you an option to have any number of dropdown boxes and JSON nodes to configure dropdown boxes.
You need to follow few steps:
Create an array of dropdown boxes.(e.g. if you have to configure a phone then you should be using dropdown of color, memory etc.)
Create a JSON object as it is created in code. Dont change the configurable items name which starts with "level1" and end with any number of nodes, As it has to be sync with the index of items of array you are creating in the first place.
Here is the data:
var Dropdowns = ["Model", "Color", "Memory","design","covers","music"];
var Data ={"phones":[
{
"oid":":000000F0:00000458:",
"level1":"3G",
"level2":"white",
"level3":"16GB",
"level4":"slim",
"level5":"Back cover",
"level6":"headphone",
"price":"£568.63",
"addToCart":"#Cart1"
},
{
"oid":":000000F0:000003DA:",
"level1":"3G",
"level2":"black",
"level3":"16GB",
"level4":"slim",
"level5":"Flip cover",
"level6":"headphone",
"price":"£615.79",
"addToCart":"#Cart7"
}]};
See the full working code here:
https://jsfiddle.net/raju_sumit/681ppgq0/5/
Try this :)
Javascript:
$.getJSON("/array.json",
function (json) {
$.each(json,
function (key, value) {
$("#id-select").append("<option value='" + value.c + "'>" + value.d + "</option>");
});
});
A pure Javascript solution: this snippet shows how to populate a dropdown select from JSON data (using id as value and name as text.
The code creates a new Option object for each item in the JSON data and appends it to the select element with appendChild(). map is used in place of a for loop.
let data = [{
"id": "1",
"name": "name_1"
},
{
"id": "2",
"name": "name_2"
}
];
var selectElement = document.getElementById('mySelect');
data.map(item => mySelect.appendChild(new Option(item.name, item.id)).cloneNode(true));
<select id="mySelect" onchange="alert(this.value)"></select>

Autocomplete in jQuery 1.4.2 jQuery UI 1.8.3

I must be thick because I cannot for the life of me get jQuery autocomplete to work. I have searched for many many examples, and it seems that most of them use an older version of jQuery. I found one fairly good example directly from the jQuery UI site: http://jqueryui.com/demos/autocomplete/#remote-jsonp So I modeled mine after that example. When I type in my input box, the little autocomplete box pops underneath the input box, but there is nothing in the autocomplete box. My data is not being loaded correctly by jQuery.
My datasource is a URL that returns JSON data. Example:
[{
"pk": 1,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "TBA"
}
}, {
"pk": 2,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "UB 2008"
}
}]
My Javascript code:
$(document).ready(function() {
$("input#id_location_address").autocomplete({
max: 10,
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
console.log( data )
response( data, function(item) {
return { label: item.address, value: item.address }
});
}
});
}
});
});
So when I console.log(data) in Firebug, it shows the object with all the data in tact. I think I am not accessing the 'address' properly in my Javascript code. See really, I just want the 'address' to pop up in the autocomplete box. How do I do this?
Thanks in advance,
Chris
I figured it out. Needed to loop through the array of json objects and then put the data into an array. I got the idea of returning an array from the defualt jQuery UI example http://jqueryui.com/demos/autocomplete/#default
$('input#id_location_address').keyup( function() {
$("input#id_location_address").autocomplete({
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
// loop through data and return as array
items = new Array();
for(item in data) items.push( data[item].fields.address );
response( items );
}
});
}
});
});
Try:
response($.map(data, function(item) {
return {
label: item.fields.address, // item.FIELDS ;)
value: item.fields.address
}
}));
Indeed, response expects an array as argument. $.map iterates over the data items and forms a new array of the return value from the passed mutator method. Once done, $.map returns the new array which will be the argument of response().
try
response($.map(data, function(item) {
return {
label: item.fields.address,
value: item.fields.address
}
}));
see the source of this demo

Categories

Resources