How to insert json data to owl carousel - javascript

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

Related

Assistance with JSON changing page contents dynamically

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

Appending content from RSS feeds to separate divs

I'm trying to display RSS using the following JS code. But when I execute this, both the RSS feeds are changed to same content (the one that is execute later) and all the feeds are appended to the same div. I think rss = this is causing the problem. Any workaround ?
HTML:
<div id="rss1" class="rss-widget">
<ul></ul>
</div>
<div id="rss2" class="rss-widget">
<ul></ul>
</div>
<div id="rss3" class="rss-widget">
<ul></ul>
</div>
JS:
function RSSWidget(id, url) {
rss = this;
rss.FEED_URL = url;
rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;
rss.renderBlogItem = function (object) {
var item = '<li class="blog-item">';
item += '<a href="' + object.link + '">';
item += '<div class="blog-item-title">' + object.title + '</div>';
item += '<div class="blog-item-author">' + object.author + '</div>';
// item += '<div class="blog-item-content">' + object.content + '</div>';
item += '</a>'
item += '</li>';
rss.widgetHolder.append(item);
}
return $.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
dataType: 'json',
success: function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
rss.JSON.push({ //add objects to the array
title: e.title,
author: e.author,
content: e.content || "",
link: e.link
});
});
if (rss.storiesLimit > rss.JSON.length)
rss.storiesLimit = rss.JSON.length;
for (var i = 0; i < rss.storiesLimit; i++) {
rss.renderBlogItem(rss.JSON[i]);
}
$('#' + id + ' li ').each(function () {
var delay = ($(this).index() / rss.storiesLimit) + 's';
$(this).css({
webkitAnimationDelay: delay,
mozAnimationDelay: delay,
animationDelay: delay
});
});
}
}
});
}
$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});
.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));
is immediately invoked. Try calling second RSSWidget within .then() anonymous function
.then(function() {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
Also, no promise is returned from RSSWidget; you can include return $.ajax(/* settings */) from RSSWidget to return the jQuery promise object from RSSWidget.

Javascript ID groupings

I'm looking to create an exception which creates 2 groupds based on their .php ID numbers.
I currently have a form that fills a table of images, and want to split them into groups using javascript.
currently the script looks like this:
var currentResults;
function init() {
getProducts();}
function getProducts() {
$.ajax({
url:"php/products.php",
dataType: "json",
data: { public: true },
success:function(result){
processResults(result);
}
});}
function processResults(results) {
currentResults = null;
if (!results && !results.products)
return;
currentResults = results.products;
for (var i = 0; i < results.products.length; i++) {
processResult(results.products[i]);}
$(".galleryitem").click(handleThumbnailClick);}
function processResult(result) {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">';
newDiv += '<div class="imageHover" style="background: ' + result.color + '"> </div>';
newDiv += '<img class="galleryImage" src="' + encodeImagePath(result.thumbnail) + '" />';
if (result.artist)
newDiv += '<div class="imageArtist">' + result.artist + '</div>';
newDiv += '</div>';
$('#gallery').append(newDiv);}
function handleThumbnailClick(e) {
if (!e || !e.currentTarget || !e.currentTarget.id)
return;
var id = e.currentTarget.id.substring(11);
window.location = 'product.php?id=' + id;}
function encodeImagePath(path) {
return path.replace(/#/g, '%23');}
I am looking for some simple advice on how to split this into multiple div's based on the product's ID number to do sections of 6 images at a time with different header text.
please advise!! thanks much!
Not sure if I got your idea right but something like this should solve your problem (in case you have a "parent" property in the products JSON you're getting from the server):
function processResult(result) {
if (typeof(result.parent) !== 'undefined') { // see if the element has a parent
var newDiv = 'markup goes here'; // if some of the markup would be reused you can create a new function for this
$('#galleryitem' + result.parent).append(newDiv); // just make sure the parent is already there
} else {
var newDiv = '<div id="galleryitem' + result.id + '" class="galleryitem">'; // default behavior that you alreay had
// code skipped for brevity
$('#gallery').append(newDiv);
}
}
P.S. You should work on your code formatting -- it can be much easier to read if formatted well.

Javascript function printing into div on separate page jquery-mobile

I have a Javascript function that prints various information from a json file and displays it in a table of contents fashion. It parses the information and prints it into a "ui-grid-b" div because i want them in rows of 3. I had a problem with the javascript printing repeatedly every time the page was opened so I added in a function to clear the div every time it prints. However, when I open a new seperate page with a "ui-grid-b" div in it it clears that and prints the table of contents again. Here's the js code and I hope you can help:
<script type="text/javascript">
var grid= new Array();
grid[0]= "a";
grid[1]= "b";
grid[2]= "c";
var j=0;
var color= new Array();
color[0]= '#00c6c4;';
color[1]= '#6fc41b;';
color[2]= '#ffbd0c;';
color[3]= '#ff84f1;';
color[4]= '#1fbbff;';
color[5]= '#ff1700;';
color[6]= '#976833;';
var k=0;
$(document).on("pageinit", "#Page1", function(){
var imp= "Json/empirical.json";
$.getJSON(imp, function(data) {
j=0;
k=0;
var toc= '';
$.each(data.tcontent, function(index, item) {
if (j > 2) { j = 0; }
if (k > 6) { k = 0; }
toc += "<div class='ui-block- ' " + grid[j] + " '>" + item.url + '<div class="grid" style="background-color: ' + color[k] + ' ">' + "<p class='gridtext'>" + item.Name + "</p>" + "</div>" + "</a>" + "</div>"
j++;
k++;
});
$(".ui-grid-b").empty().append(toc);
});
});
</script>
Assign your toc grid a unique ID:
<div id="theTOC" class="ui-grid-b"></div>
Then in your code instead of:
$(".ui-grid-b").empty().append(toc);
do
$("#theTOC").empty().append(toc);
Make sure this id is unique accross all pages. Also make sure your pages have unique IDs (i.e. only one page called "Page1").

Placing a div only after clicked object

Buildgames returns rows:
<a>....</a>
<a>....</a>
When I click on each a the Buildcar_s function returns all the data inside an alert.
Instead of this alert I want to put all the results in a div under each a, so it would look like:
<a>.....clicked ...</a>
<div>....
...
</div>
<a>....not clicked...</a>
<a>....not clicked...</a>
<a>....not clicked...</a>
How can we put a div only under the a which was clicked?
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += 'mmmmmm<br/>';
});
place += '</div>';
return place;
}
Try this, relevant changes have been commented:
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
var $a = this;
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
// this inserts the HTML generated from the function,
// under the A element which was clicked on.
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += '<div style="float: right;"> ' + this.CITY + ' ' + '</div><BR />' + +'<br/><br/>';
});
place += '</div>';
return place; // returns the string created, as opposed to alerting it.
}

Categories

Resources