Evaluating JSON dynamic name - javascript

I want to display a database value and build a bootstrap grid, building the bootstrap grid was easy however displaying the data isn't as easily built.
Normally I would call the items I wanted in the loop like this x[i].DIAG;. However I am building a dynamically variable name "s": var s = i*cNum+j so that I can call the item dynamically x[s].DIAG. When I display the value with console.log(s), I see the values I want. However, when I try output the data it breaks. Any suggestions would greatly be appreciated.
JSON example:
0: Object
DIAG:"Anaplastic"
DIAGID:13
Code:
function loadDiag(){
$.ajax({type: "GET"
, dataType: "json"
, url: "CFCs/lookUps.cfc"
, data: {method: "Diag_rlu"}
, success: function(data){
var x = data.items;
console.log(x)
var rNum = x.length / 6 //number of rows
var cNum = 6 // number of colums
var str = '';
for (var i = 0; i < rNum; i++) {
str += '<div class="row" id="'+i+'">';
for (var j = 0; j < cNum; j++) {
var s = i*cNum+j
if(s <= x.length){
str += '<div class="col-xs-2">'+x[s].DIAG+'</div>';
} else{
str += '<div class="col-xs-2"></div>';
}
}
str += '</div>';
}
$('.diagnosis').html(str);
}
});
}

Related

Nested loop only rendering last indexed item using jquery appendPe

Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show.
function displayDrinkData(drinkName) {
var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
var results = response.drinks;
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
var eachDrink = results[i];
var drinkDiv = $("<div>");
var drinkName = results[i].strDrink;
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k])
}
var pOne = $("<p>").text("Drink name: " + drinkName);
var drinkInstructions = results[i].strInstructions;
var pTwo = $("<p>").text("Instructions: " + drinkInstructions);
var drinkImage = $("<img>");
drinkImage.attr("src", results[i].strDrinkThumb);
drinkDiv.append(pOne);
drinkDiv.append(ingList);
drinkDiv.append(pTwo);
drinkDiv.append(drinkImage);
$("#drinks-view").append(drinkDiv);
}
})
}
Because var ingList is inside loop, not appending, but creating a new one every time.
var ingList = $("<ul>");
for (var k = 1; k < 16; k++) {
console.log(eachDrink['strIngredient' + k]);
ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k]));
}
Declare variable outside loop, and append <li> for each element.

Create a table from json (JSON.stringify(res[0]) ) - output in a string - should be transformed to a table in html

I need to create a table from JSON, I'm getting output in a string and it should be printed in table format in HTML
function apicall(){
var id = document.getElementById('idval').value;
var url1 = '**********************';
var token = sessionStorage.getItem('MyUniqueUserToken');
var data1 = {"ip":id};
var success = {};
var dataType = {};
$.ajax({
url: url1,
data: data1,
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'token '+token);},
success: function(res) {
document.getElementById('output').innerHTML =JSON.stringify(res[0]);
}
});
}
enter image description here
Guessing that res is the response as a JSON so instead of
document.getElementById('output').innerHTML =JSON.stringify(res[0]);
you have to put your response into a loop (Given you have an empty table with cells=fields output0 to output4
var i=0;
response.data.forEach(function(field) {
//here you create the table cells if there are 5 fields
that would be 5 cells as I do not know the structure just
pseudo code
document.getElementById('output'+i).innerHTML = JSON.stringify(res[i]);
i = i+1;
}
if you want to semi dynamicly create table rows you have to have a table with header (footer) row fix and the tabelbody as an anchor to whichyou append the created rows could look like follows (partly pseudo code) -PLAIN vanilla javascript as I do not like jquery:
// We need a table definition for creating headers and interpreting JSON date
var tdataRow = [{
"output0" : field.output0,
"output1" : field.output1,
"output2" : field.output2,
"output3" : field.output3;
"output4" : field.output4
}];
// Then in jour ajax
response.data.forEach(function(field) {
var columnHeadings = Object.keys(tdataRow[0]);
var tableRef = document.getElementById("tbody" + "my_test_table");
var columnCount = 5; // Could be derived from number of headings
var tableLength = tableRef.getElementsByTagName("tr").length;// we get the number of the existing table rows
var trowID = tableLength + 1; // we append at the end of existing rows
var tableRow = tableRef.insertRow(tindex);
for (var j = 0; j < columnCount; j++) { /* Each column */
var cell = tableRow.insertCell(-1);
cell.setAttribute("id", columnHeadings[j] );
var obj = tdataRow[0];
cell.innerText = obj[columnHeadings[j]]; // we get the field names from the header
}
tableRow.setAttribute("id", "row" + "my_test_table" + j );
// examples how to style and use classes
tableRow.classList.add("table");
tableRow.classList.add("clickable-row");
tableRow.setAttribute("align","center");
// if you want to catch clicks on the row
tableRow.addEventListener("click", function(){
// do something with the row e.g. highlight/ get values etc
}
}
The second solution can be converted into a fully automated/dynamic solution where everything is created from the JSON - but small steps first.

Accessing data in Google Maps PHP with jQuery

I'm having trouble correctly accessing data in Google Maps API php.
Heres what example data looks in php:
{"destination_addresses":["Destination address"],"origin_addresses":["Origin address"],"rows":[{"elements":[{"distance":{"text":"3.3 km","value":3314},"duration":{"text":"6 mins","value":334},"status":"OK"}]}],"status":"OK"}
Heres my .js:
$(function(){
$("#button").click(function(){
var start = $("#start").val(); //gets start and end values from input fields, and passes them to .php which is not visible here.
var end = $("#end").val();
$.ajax({url: "googlemaps.php",
method: "GET",
data : { "start" : start, "end" : end },
success: function(result) {
print(result);
},
error: function(xhr){
alert("Error: " + xhr.status + " " + xhr.statusText);
}
});
});
});
function print(result){
var length = "";
for(var i = 0;i < result.rows.length;i++){
length += result.rows[i].text+ "<br/>";
$("#div").html(length);
}}
It should calculate the distance between two addresses, and it currently returns unidentified (which is ok), since
length += result.rows[i].text+ "<br/>";
is not correct. I have no idea how to access value "text":"3.3 km", or it's equivalent in my code. I know it is an object inside "distance", which is an array item of "elements", which is an array item of "rows".
Its structured like:
rows[0].elements[0].distance.text
You might not need the loop, but if you were to use it you would do something like.
for (var i = 0;i < result.rows.length; i++) {
for (var k = 0;k < result.rows[i].elements.length; k++) {
length += result.rows[i].elements[k].distance.text + "<br/>";
}
}
$("#div").html(length);
If your array is result, then you can access the distance by using this:
var distance = result['rows'][0]['elements'][0]['distance']['text'];

Jquery ajax send json

Javascript:
function add_content(count)
{
var result = {};
var row = new Array();
for (i = 0; i < count; i++)
{
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
$.ajax({
url: "ajax-functions.php",
data: {json_data: JSON.stringify(row)},
type: 'post',
success: function (output) {
alert(output);
}
})
}
Php:
$img_desc = json_decode($_POST['json_data'],TRUE);
$count = count($img_desc);
echo 'count:'.$count;
print_r($img_desc);
I want to send json to from JS to PHP. This above code works well, but it send the last data of the for loop is set in all the objects.
How to fix it? Is this right way?
Thanks.
Push a new object on each round of the loop into to the array
for (var i = 0; i < count; i++) {
row.push({
"img_src": $("#img_" + i).attr('src'),
"desc": $("#desc_" + i).val()
});
}
fiddle
Move result declaration inside for:
var row = new Array();
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}
or it can be done more elegantly:
var row = new Array();
var result;
for (i = 0; i < 10; i++)
{
result = row[ row.push({}) - 1 ];
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
}
You can make the keys of result array also dynamic
Since you are not making it dynmamic, its getting over ridden in the next loop
EDIT:
for (i = 0; i < count; i++)
{
var result = {};
result['img_src'] = $("#img_" + i).attr('src');
result['desc'] = $("#desc_" + i).val();
row.push(result);
}

Undefined variable error when parsing json

I'm trying to parse the json grabbed from here. Basically what I do is iterate over the items, sort them, then display them. But I get an error saying data.data.children[i] is undefined.
I can't think why it's doing it though?
var json = 'http://www.reddit.com/reddits/mine/.json';
GM_xmlhttpRequest({
method: "GET",
url: json,
onload: reddits
});
function reddits(response){
var txt = response.responseText;
var data;
var suggested = document.getElementById('suggested-reddits');
if(window.JSON && JSON.parse){
data = JSON.parse(txt);
}
else{
data = eval("("+txt+")");
}
suggested.innerHTML += '<span>reddits you\'re subscribed to </span> <ul id="rsub"></ul>';
GM_addStyle('#rsub{width: 500px;}');
var reddits = new Array();
var rsub = document.getElementById('rsub');
for(i = 0; i <= data.data.children.length; i++){
var r = data.data.children[i].data.display_name;
reddits.push(r);
}
sort(reddits);
for(i = 0; i <= reddits.length; i++){
rsub.innerHTML += '<li>' + reddits[i] + '</li>';
}
}
for(i = 0; i <= data.data.children.length; i++){
var r = data.data.children[i].data.display_name;
reddits.push(r);
}
Clear problem is in the for statement. Change the i <= data.data.children.length to i < data.data.children.length. Note the inequality change.
Since arrays in Javascript are 0-indexed, the element at i = data.data.children.length does not exist.
You should probably do the same things for the reddits.length loop.

Categories