Assistance with JSON changing page contents dynamically - javascript

I am working on a website and I am looking to make the recipes pages dynamic. I created a JSON test database, created a JS file that retrieves values from the JSON file and displays them in appropriate divs on the page.
What i want to do is be able to choose the respectful JSON for each recipe and display it on the same page when a user clicks a link in the sidebar without having to create a ton of blank HTML pages with the same divs.
Below is my code. Hoping someone can help guide me thanks!
(function() {
'use strict';
var url = 'my json url';
$.getJSON(url, function(json) {
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
});
})();
new code`(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('#pasta').click(function(){
$('#recipeIngredients').empty();
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = '';
$.getJSON(url,callback);
})();`

to achieve code reusability , try calling the $.getJSON() with a reusable function (callback) on click of the link in the sidebar
(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
.... //rest of the code
...
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('.sidebarLink').click(function(){
$('#recipeIngredients').empty()
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = 'my json url';
$.getJSON(url,callback);
})();

Related

I'm not sure why this isn't XML information isn't printing to the screen

I have written this code which is supposed to print the information from the xml file into a list for each faculty member. I want to eventually place all of these into a table, but need to know how to print them to the screen first.
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseXML);
var faculty = this.responseXML.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++) {
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += "<li><a href = " + name + title + "</a></li>";
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
}
};
xhttp.open("GET", "faculty.xml", true);
xhttp.send();
}
window.onload = init;
Here is the XML file:
<facultyInfo>
<faculty>
<name>Prof A</name>
<title>Professor and Program Coordinator</title>
<office>CI 555</office>
<phone>(999-999-9999</phone>
<email>ProfA#school.edu</email>
</faculty>
<faculty>
<name>Prof B</name>
<title>Visiting Professor</title>
<office>CI 333</office>
<phone>999-999-9999</phone>
<email>ProfB#school.edu</email>
</faculty>
</facultyInfo>
This line:
strOut += "<li><a href = " + name + title + "</a></li>";
... is both malformed and probably not what you intended. Between the missing quotes for the href attribute, missing the ">" to close off the <a> start, and not putting any text in between <a></a>, this results in a link tag where the link destination (href) is set, but the actual text to show to the user is not set. I don't see any links in your XML (maybe that is for the future), so for now you probably want something like this:
strOut += '<li>' + name + ', ' + title + '</li>';
Here is a quick demo with your XML input:
<div id="output"></div>
<script>
var xmlString = '<facultyInfo> <faculty> <name>Prof A</name> <title>Professor and Program Coordinator</title> <office>CI 555</office> <phone>(999-999-9999</phone> <email>ProfA#school.edu</email> </faculty> <faculty> <name>Prof B</name> <title>Visiting Professor</title> <office>CI 333</office> <phone>999-999-9999</phone> <email>ProfB#school.edu</email> </faculty> </facultyInfo>';
var xmlDoc = (new DOMParser()).parseFromString(xmlString,'text/xml');
// var faculty = this.responseXML.getElementsByTagName("faculty");
var faculty = xmlDoc.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++){
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += '<li>' + name + ', ' + title + '</li>';
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
</script>

How to insert json data to owl carousel

I have a JSON data from FB api reviews, and I want to insert the data from the JSON to an owl carousel div elements. I want each review to be created in a separate div element and that div element to be inside the owl carousel, and to work as carousel.
In the HTML I only have this:
<div id="carousel" class="owl-carousel" style="color: white;">
</div>
Previously I have set up the carousel, now my question is how to take the data from the JSON and insert in the div owl-carousel class but I want the divs that will be inserted inside to take the class owl-item, etc.
Here is the JavaScript:
$(document).ready(function () {
var url = "https://graph.facebook.com/v3.2/...";
$.getJSON(url, function (data) {
var items = [];
$.each(data.data, function (i, obj) {
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
}); //Here I get the review text and the created date of the review
//I want to create div element for each review and insert that div in the owl carousel
});
});
This is what I have tried so far:
$(document).ready(function () {
var url = "https://graph.facebook.com/v3.2/...";
$.getJSON(url, function (data) {
var items = [];
$.each(data.data, function (i, obj) {
//$('#target').append($('<div/>', { id: 'dummy' + i }))
var text = '<p class="review_text">' + obj.review_text + '</p>'
var date = '<p class="date">' + obj.created_time + '</p>'
a = counter();
$("#carousel").find("[data-index='" + i + "']").append(text, date)
});
$('#scripts').append('<input type="number" id="spam_key" value= ' + a + '>');
});
var wrapper = document.getElementById("carousel");
var myHTML = '';
for (b = 0; b <= 230; b++) { //but here instead of 230 I want to get the value of a
myHTML += '<div id="review" data-index=' + (b) + '></div>';
}
wrapper.innerHTML = myHTML
});

How to sort firebase getDownloadURL() results with javascript?

This function is displaying images from firebase urls:
function updateTimeline(){
var ul = document.querySelector("#timeline ul");
ul.innerHTML = "";
var db = firebase.database().ref("phoodos/");
var list = db.orderByChild("timeStamp");
list.on("child_added", function(child) {
var selfie = child.val();
// Retrieve the image file
var storageRef = firebase.storage().ref();
var imageRef = storageRef.child(selfie.path);
imageRef.getDownloadURL().then(function(url){
var li = "<li><figure>";
li += "<img src='" + url + "' width='100%' alt='Phoodo'>";
li += "<figcaption>By " + selfie.user + ": " + selfie.timeStamp + "</figcaption>";
li += "</figure></li>";
ul.innerHTML += li;
})
});
}
Results of orderByChild are sorted, but results from getDownloadURL() are not sorted.
How can I sort the images retrieved by getDownloadURL() before adding to my html?
One trick is to insert the HTML in the correct order:
var ul = document.querySelector("#timeline ul");
ul.innerHTML = "";
var db = firebase.database().ref("phoodos/");
var list = db.orderByChild("timeStamp");
list.on("child_added", function(child) {
var selfie = child.val();
// Retrieve the image file
var storageRef = firebase.storage().ref();
var imageRef = storageRef.child(selfie.path);
var li = document.createElement("li");
ul.appendChild(li); // this ensures the <li> is in the right order
imageRef.getDownloadURL().then(function(url){
var html = "<figure>";
html += "<img src='" + url + "' width='100%' alt='Phoodo'>";
html += "<figcaption>By " + selfie.user + ": " + selfie.timeStamp + "</figcaption>";
html += "</figure>";
li.innerHTML = html;
})
});

Modifying innerHTML in nested get() jQuery

I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?

Image Currently Unavailable from Flickr

In my Firefox OS app i use Flickr API to show relevant images, My URL for the call is like this.
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&lat=42.86366&lon=-75.91438&radius=3&format=json&nojsoncallback=1
and i use created a function to call the flicker api for the images. This is the function where i create the URL with the api key and latitude and longitude for the api call
function displayObject(id) {
console.log('In diaplayObject()');
var objectStore = db.transaction(dbTable).objectStore(dbTable);
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
if (cursor.value.ID == id) {
var lat = cursor.value.Lat;
var lon = cursor.value.Lon;
showPosOnMap (lat, lon);
// create the URL
var url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
url += '&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
url += '&lat=' + lat + '';
url += '&lon=' + lon + '';
url += '&radius=3';
url += '&format=json&nojsoncallback=1';
$.getJSON(url, jsonFlickrFeed);
return;
}
cursor.continue();
} else {
$('#detailsTitle').html('No DATA');
}
};
}
This function gets the JSON object received from flickr. This function displays the thumbnails of the images in a jquery mobile grid.
function jsonFlickrFeed (data) {
console.log(data);
var output = '';
// http://farm{farmId}.staticflickr.com/{server-id}/{id}_{secret}{size}.jpg
for (var i = 0; i < data.photos.photo.length; i++) {
// generate thumbnail link
var linkThumb = '';
linkThumb += 'http://farm' + data.photos.photo[i].farm + '.staticflickr.com/' + data.photos.photo[i].server + '/' + data.photos.photo[i].id + '_' + data.photos.photo[i].secret + '_s.jpg';
// generate Full image link
var linkFull = '';
linkFull += 'http://farm' + data.photos.photo[i].farm + '.staticflickr.com/' + data.photos.photo[i].server + '/' + data.photos.photo[i].id + '_' + data.photos.photo[i].secret + '_b.jpg';
if (i < 20)
console.log(linkThumb);
//console.log(linkFull);
var title = data.photos.photo[i].title;
var blocktype = ((i % 3) == 2) ? 'c' : ((i % 3) == 1) ? 'b' : 'a';
output += '<div class="ui-block-' + blocktype + '">';
output += '<a href="#showphoto" data-transition="fade" onclick="showPhoto(\'' + linkFull + '\',\'' + title + '\')">';
output += '<img src="' + linkThumb + '_q.jpg" alt="' + title + '" />';
output += '</a>';
output += '</div>';
};
$('#photolist').html(output);
}
Then finally this function show the full screen view of the image. When the user taps on the thumbnail a larger image is taken and shown.
function showPhoto (link, title) {
var output = '<a href="#photos" data-transition="fade">';
output += '<img src="' + link + '_b.jpg" alt="' + title + '" />';
output += '</a>';
$('#myphoto').html(output);
}
My problem is that, i get the JSON object with the images by calling the API. i have console.log() where i output the json object and i checked all the image info is there. But when i go to the grid view and even the full view i get the default image that states that the This image or video is currently unavailable. I can't figure out what im doing wrong here.. Please help.
You may be requesting an image size that flickr does not have for that image. You are appending "_s", "_q" and "_b" to select a few sizes - so perhaps those are not available. You can check the flickr API 'photos.getSizes' to see what sizes are available. The Flickr API seems to be pretty inconvenient sometimes.
https://www.flickr.com/services/api/flickr.photos.getSizes.html

Categories

Resources