Calling and json file and displaying it on html - javascript

I want to display images from my json file on a html page and organise them into rows of 3 or 4. Below is an example of the layout I want my page but this is hard coded,I have included images because I have having difficulty pasting the code (I can put this on fiddler) don't mind some of the word under the pictures some p tags needed taken out:
HTML:
<div id="container">
<div class="row">
<div class="product-container"> </div>
<div class="col-sm-4">
<img src="Image/iphone5.jpg" alt="StrappyMeshInsertDress" style="width:200px;height:250px">
<p><span> class="bold">Iphone5s</span><br />
</div>
Here is a snip from my json file:
json data
I am using this script to call the data although it has not been calling the json file:
the script
I have positioned the images when hard coding like this:
I have been at this for over a day and cannot get it to work, If anyone has any ideas on how to get this to work I would be very grateful.
Kind regards!

Please make sure that you are appending JSON data dynamically so please remove the HTML content, or only make a parent container who will hold all this Output data.Make a JSON file with the name 'iproducts.json' on the same path.
$.getJSON('iproducts.json',function(products){
var output=" <table border='1'><thead><th>Product_id</th><th>Info</th><th>Imgpath</th><th>Price</th><tbody>";
$.each(products.appleitems,function(index,value){
output+="<tr><td>" + value.Product_id + "</td><td></td></td><td>" + value.Information+"</td><td>"+"<img src ='images/" + value.Imgpath + ".jpg' alt='applepro' id='appleinf'" + value.Price +"</td><td>"
});
output+="</tbody></table>";
console.log("output =" + output);

Related

Store JSON information within a HTML file or the other way around

That title might be a little confusing but I don't know how to put it otherwise. I have some JSON encoded data in a .json-file:
{"foo":"bar", "bar":"foo", "far":"boo"}
and some HTML content in a .html-file:
<h1>I'm a Title</h1>
<p>Lorem Ipsum</p>
<br>
<img src="./media/foo.png">
There is a jQuery script that takes the data from both files ($.getJSON() and $(#div).load()) and creates a page with some predefined head, uses the html as content and the json data to create some buttons (key=destination & value=name) on there.
Because the project has many of these pages I would love to have only one file that holds both my HTML content AND the JSON data so I had all I needed for one page would be a single file access. So the question really is: How can I store both JSON and HTML data in one file so jQuery can access, distinguish and process it?
This is part of an electron application but I'm not sure if that even matters for that question.
The content of the json file assuming it is a json object can be assigned to a javascript variable in the html document in a script tag.
Then to refer to, for example foo, you use theJsonObject.foo;
With the following javascript snipet you can see inthe browser's console the name of each property an the value.
How you mix this in your current code depends on how you are writting it. But make sure the variable is declared before you use it.
for (let prop in theJsonObject) {
console.log( prop + ": " + theJsonObject[prop] );
};
<html>
<head>
....
<script>
var theJsonObject = {"foo":"bar", "bar":"foo", "far":"boo"};
</script>
</head>
<body>
....
</body>
</html>

Angular 1.5.5 render html based on return value of an $http call

I want to know the best way to proceed given the following information:
I have a controller which makes 2 http calls using a factory.
DataFactory.getTestDisplaySections(testID).then(function (response) {
$scope.testSections = JSON.parse(response.data);
});
DataFactory.getTestObjectByTestID(testID).then(function (response) {
$scope.testObject = JSON.parse(response.data);
});
The call returns two arrays. I want to generate html with data from the array embedded in it. Right now, my template for the controller contains only an empty shell of a page.
<div class="container">
<div class="row">
<div ng-bind-html="sectionHTML"></div>
</div>
</div>
The sectionHTML above is my variable which contains the html markup for the entire page.
The first call returns data that gives me names of panels that are to be displayed on the page. These could be 4 or more. I want to use the following html to display each panel.
$scope.sectionHTML = '<div class="col-lg-6">'+
'<div class="panel panel-primary">'+
'<div class="panel-heading lead">' + panelDiaplayName + '</div>' +
'<div class="panel-body">'+
'<div id="test_info" class="col-lg-12">' +
'</div>'+
'</div>'+
'</div>'+
'</div>'
Should I just go through the panel data in a for loop and create the html that way for each panel?
When I try to add the panelDisplayName using {{}} It shows up as just {{panelDisplayName}} will this be an issue, every time I have to evaluate an angular expression? How can I resolve this issue?
Second, I have other information that I need to display within each of the panels. This comes from the second http call. Each panel will have details in it and each piece of information will be editable. Can anybody help with the best way to do it?
I can give more explanation if anyone needs it.
Thanks
Paras
I think you are asking about multiple issues here, so I will try to help solve the first two, looping through your array to build your page and helping you get the {{}} data-binding to work.
For your panels, don't use a for loop and build html in your controller. You are using angular, the angular way is using ng-repeat. You add this to your html template and it will build the dom by iterating over your array. In your example:
.html
<div class="container">
<div class="row">
<!-- this is where we are iterating over the array (ng-repeat) -->
<div class="col-lg-6" ng-repeat="section in testSections">
<div class="panel panel-primary">
<!-- section is the current item being iterated in the array, so we are printing the displayName for the section -->
<div class="panel-heading lead">{{section.panelDiaplayName}}</div>
<div class="panel-body">
<div id="test_info" class="col-lg-12">
</div>
</div>
</div>
</div>
</div>
</div>
As for the data-binding. My assumption here is that you aren't adding ng-app and/or ng-controller to elements that encompass your data-bindings. For example:
.html
<body ng-app="yourApp" ng-controller="yourController">
<h1>{{testMessage}}</h1>
</body>
app.js
var app = angular.module('yourApp').controller('yourController', ['$scope', function($scope) {
$scope.testMessage = "Hello World";
}])
As for your second question about dealing with data that will be edited, I recommend giving that a shot yourself. Look in to angular forms and ng-model. Those should help you get started. After giving that a shot, if you are still struggling, ask a new question for the specific issue you are struggling with.

how to dynamically action an angular ng-include command

Is it possible to dynamically add an ng-include element to a HTML page and have it actioned?
I have a Drag N Drop application where you can drag an element onto the page and in the drop zone the element is replaced with a more detailed element. For examples you drag a box that says Calendar and when it is dropped a calendar is presented. To be clear a new Element is created and added to the DOM, it does not exist before the drop.
When the element is dropped, I'm hoping that I can replace it with a chunk of HTML that looks like below. Instead of having the markup defined in a string like it is at the moment which is not very nice:
<div class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'>
<span class='glyphicon glyphicon-remove'></span>
WIDGET NAME
<spanclass='glyphicon glyphicon-cog'></span>
</h3>
</div>
<div class='widgetContainer' ng-include="'widgets/widget.html'"></div>
</div>
When the above HTML is inserted into the page the referenced HTML file is not included.
What I would like to happen is a HTML file is loaded containing the widget markup and included at the appropriate position.
I'm new to Angular so I don't know if this is because:
dynamically adding ng-include isn't supported
whether I need to do something with the controller to handle this logic
should I be using the tag instead of the attribute?
it just isn't possible.
Please provide examples with solutions, as I said I'm new to Angular.
Thanks
UPDATE
The code used to created the HTML that I want to dynamically add to the page looks like this
$("#template").append(
" \
<div class='panel panel-default'>\
<div class='panel-heading'>\
<h3 class='panel-title'>\
<span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeElement(this)'></span>\
" + widgetDetail['serviceName'] + "\
<span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
</h3>\
</div>\
<div class='markupContainer' ng-include=\"'widgets/" + id +".html'\"></div>\
</div>\
"
);
I've uploaded the complete code to GitHub. The drag and drop aspects are being handled currently by HTML5 javascript, which can be seen in the file /public/javascripts/js_dragndrop.js. The new widget being added to the page (the code above) is in /public/javascripts/jq_dragndrop.js
I'm in the prototyping phase trying to work out the DragNDrop elements so don't expect high quality code :)
I found a way of achieving what I wanted by moving the HTML5 drop and drop code into AngularJS directives and then (using this [ Compile dynamic template from outside of angular ] as a guide) got the html templates being loaded where I wanted them.
The main code change looks like this:
angular.element(document).injector().invoke(function ($compile) {
var widgetDetail = widgets[e.dataTransfer.getData('Text')];
var obj = $("#template");
var scope = obj.scope();
obj.append(
"<div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>\
<span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeWidget(this)'></span>\
" + widgetDetail['serviceName'] + "\
<span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
</h3></div><div class='markupContainer' ng-include=\"'widgets/" + widgetDetail['serviceId'] + ".html'\"></div>\
"
);
$compile(obj.contents())(scope);
scope.$digest();
});
You can find the full code in the Git Project /public/controllers/template.js if you are interested.

Removing HTML from a jQuery .append()

I have a Parse.com backend and am rendering its data, ultimately, with a jQuery append, like this:
$(".albums").append(
"<div class='col-xs-6 col-6 col-sm-3 col-lg-3'><div class='flip animated fadeInDown' style='-webkit-animation-delay:" + i * 0.1 + "s'><div class='card'><div class='album front' style='background-image:url(" + bigImg + ")'><img class='artwork' src='" + artwork + "' alt='" + collectionName + "' /></div><div class='album back' style='background-image:url(" + back + ")'><img class='artwork' src='" + back + "' alt='" + collectionName + "' /></div></div></div></div>");
It's a for loop hence the need for the various HTML elements and their classes. I know it's an appalling, shameful way to do it (and I believe it's causing a memory leak).
My questions are: How can I remove as much of the HTML from this append statement as possible? Should I be using a templating language?
If you think you might want to use a templating language you can start by building your own, super simple, template.
Simply replace
"some string stuff " + someValue + " some more stuff"
// instead
var myTemplate = "some string stuff {someValue} some more stuff";
// now render
myTemplate.replace('{someValue}', someValue);
It's easy to go further, and wrap this in a function to "render" that takes an object as an argument and iterates over keys. Done carefully this will provide you a subset of the functionality provided by "off-the-shelf" templating libraries so you can always cut-over later.
This will allow you to predefine your "template" and render using the data input provided. The next question is where do you want to define your template. Generally you would relocate it to a separate free-standing file that the designers would have access to, perhaps in a "templates" directory. But then you have to load it.
If you have lots of templates, some libraries would allow you to pack them together in one file, load the file, then ask the library for a specific template by name. Your designers would then control this file and the CSS that goes with it. If you have a lot of this, then the architectural overhead starts to make sense.
Whether you want to go down that road really depends on your specific circumstances and the structure of your project team.
I like Handlebar for this sort of thing.
This would be the template
<script id="albumsTemplate" type="text/x-handlebars-template">
<div class='col-xs-6 col-6 col-sm-3 col-lg-3'>
<div class='flip animated fadeInDown' style='-webkit-animation-delay:{{delay}}s'>
<div class='card'>
<div class='album front' style='background-image:url({{bigImg}})'>
<img class='artwork' src='" + artwork + "' alt='{{collectionName}}' />
</div>
<div class='album back' style='background-image:url({{back}})'>
<img class='artwork' src='" + back + "' alt='{{collectionName}}' />
</div>
</div>
</div>
</div>
</script>
And then you would use it like this:
var source = $("#albumsTemplate").html();
var template = Handlebars.compile(source);
var html = template({delay:i*0.1,
bigImg:bigImg,
collectionName:collectionName,
back:back});
$(".albums").append(html)
Adding html() to the call should do it. That'll return the html inside of .albums. To get everything including .albums you do $('.albums').append(...).parent().html().

jQuery Mobile JSON parsing

I'm trying to make a cross platform mobile application using jQuery Mobile.
I have a JSON string that displays information about a specific object (check it out here: http://app.calvaryccm.com/mobile/web/teachings/json?callback=?) and I want it to turn it into a list view that connects to a single item view. The problem is, the listview isn't displaying like a list at all. It is almost like HTML without CSS. Check it out here: http://mbeta.calvaryccm.com/#teachings
This is the Javascript for parsing the JSON string:
<!-- Getting Teaching Data -->
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("http://app.calvaryccm.com/mobile/web/teachings/json?callback=?",
function (data) {
//remove any characters from the query that might be unsafe to use as an ID for a page
//data.pageId = data.MessageNumber.replace(/[^\w]/, "");
//Feed the data to the template and add the new page to the body.
var res = $("#teachingTemplate").tmpl(data); //.appendTo(document.body);
$("#teachings").append(res);
//Grab a reference to that shiny new page
//var newpage = $("#" + data.pageId);
});
});
//Makes date readable
function GetDate(jsonDate) {
var value = new Date(parseInt(jsonDate.substr(6)));
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
}
This is supposed to be the list view:
<script id="teachingTemplate" type="text/x-jquery-tmpl">
<div id="${MessageNumber}">
<div data-role="header">
<a data-icon="arrow-l" href="#" data-rel="back">Back</a>
<h1>${Title}</h1>
</div>
<div data-role="content">
<div class="teachingsForm">
<ul data-role="listview">
<li><a href="singleTeachingView" class="tableImage">
<img src="" alt=""/>
<h3>${Title}</h3>
<p>${Speaker} - ${GetDate(MessageDate)} - ${MessageNumber} {{if Book != null}} - ${Book.BookName} ${ChapterVerse}{{/if}}</p>
</a>
</li>
</ul>
</div>
</div>
<div data-role="footer">
<h4>2011 Calvary Chapel Melbourne</h4>
</div>
I cannot figure out why my listview isn't displaying right. If you want to see it in action look here: http://mbeta.calvaryccm.com/#teachings . I need help getting my listview to display right and direct to the right page.
It looks exactly like what your template says it should look like. Note that each of your <ul> elements only has one <li> element in it.
Your template starts off with an outer <div>, and then there's a "header" <div> with the <h1> title. Then there's the "content" <div>, and ultimately the <ul>, and finally the "footer". That's what your result page looks like. If you want to do some sort of iteration, well, you'll have to explicitly do that in your template, because otherwise the template code will assume you just want it to re-apply the template to each object in the array you pass it.
There's nothing wrong with the "JSON parsing". Note that in your JSON, there's no need to quote "/" characters with "\" and in fact (though it doesn't matter for JSONP) it's not valid JSON.
edit — OK so now that I've pulled my head out from wherever it was I think I see what you're doing. The problem may be that you just need to call
$.mobile.changePage();
at the end of your JSONP callback function. However I note that your "$.mobile" doesn't have a "changePage()" function ... I don't know what that means. You're using a pretty old version of jQuery too.

Categories