How to display images using Javascript and JSON - javascript

I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}

Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;

Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);

You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>

Related

Get value from a JSON file with multi dimensional array using jQuery $.getJSON method

I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo

Place elements in a single div in jQuery

I am new to jQuery and I am working with an API to do the following.
Get Multiple values from the API like name, place, weather forecast etc.
I have a bootstrap structure with the following code:-
<div id="place_here" class="row">
</div>
I want to place the data that I get from the API in this DIV.
Only thing that I want to do is get put all that data into a single div and place that div into above row div to create a beautiful table like structure. Something like this:-
var str = '<div class="col-md-4">' + newoverview + '</div>';
(newoverview is a string from JSON that I get. However that is only a single value that I want to place in my div class = "col-md-4" tag above. I want to insert more values as well.
Problems:-
I cannot(or don't know) how to use global variable in JQuery. Whenever I log a variable value in console it give me a null . I know that's because JSON is asynchronous but I don't know a work around this.
I tried using multiple functions and passing values one by one and adding div by div. However that is not doing what I want to do and gives a messed up structure.
How can I collect all the required values that I get in a JSON and combine them in a single div and place it in a div in my HTML structure.
Edit:- Code
$(document).ready(function(){
$("#Search_Button").click(function() {
var name;
name = $("#value").val();
if(!name){
console.log("Enter a name");
}
search(name);
});
function search(name){
var url = "url_here";
$.getJSON(url,function(data){
$.each(data.results,function(i,j){
displayImage(j.path);
displayOverview(j.id);
});
});
}
function displayOverview(id){
var url = "url_here";
$.getJSON(url,function(data){
var overviewx = data.overview;
var newoverview='';
for(var x=0;x<overviewx.length && x<100 ;x++){
newoverview+=overviewx[x];
}
var str = '<div class="col-md-4">' + newoverview +
'</div>';
$("#place_here").append(str);
});
}
function displayImage(id){
var url = "url_here";
var str = '<img src="' + url + '"</img>';
$("#place_here").append(str);
console.log(str);
}
});
I want to place both(and maybe more) tags in a single div from displayOverview and from displayImage and place that div into my main HTML Structure.
This is just an exemple !
to prevent asynchronous processing,we use callbacks
function getItem(){
var dfd = jQuery.Deferred();
var url_to_json = 'json/test.json';
$.getJSON(url_to_json, function(data) {
dfd.resolve(data);
});
return $dfd.promise();
}
when you need a the response you just :
getItem.done(function(data){
console.log(data);
});

Get image names in html using JavaScript

How can I pick up image name in html using JavaScript? I searched google and there are some documents about how to get image name on <img> tag,
var filename = tag.replace( /^.*?([^\/]+)\..+?$/, '$1' );
But it return just one name of images. What I'm going to do is get all images name. Imagine the html below,
<html>
<body>
<div class="imagebox">
<img src="/some/path/imageOne.jpg">
<img src="/some/path/imageTwo.jpg">
<img src="/some/path/imageThree.jpg">
</div>
</body>
</html>
after magic, return
imageOne, imageTwo, imageThree. How can I do this..?
Add the following Javascript code at the bottom of your html page :
Solution for browser environment :
var images = document.getElementsByTagName('img');
var images_urls = [];
var images_names = [];
var tmp;
for(var i=0;i < images.length;i++){
images_urls[i] = images[i].getAttribute('src');
tmp = images[i].getAttribute('src').split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
and now images_names is an array containing the image names, in this case imageOne,imageTwo and imageThree
Solution for Node.js environment:
lets say you have images url stored in images variable like this :
var images = ["/some/path/imageOne.jpg", "/some/path/imageTwo.jpg", "/some/path/imageThree.jpg"];
you can use Regex, but in this case you can do it easily without using Regex, just split each image url and grab the last part of it, pretty simple, something like this :
var images_names = [];
var tmp
for(var i=0;i < images.length;i++){
tmp = images[i].split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
It is the same solution for both Browser and Node.js environment except for the way you get the elements.
Hope this helps.

What is the best way to create a list of text and images, using JavaScript and little to no HTML?

So I have successfully made a list using strictly HTML and CSS and that was simple enough. Now, I want to create the same list, while using JavaScript, for the most part. I'm not so sure why its so confusing for me.
Now I understand that in my HTML file, I must create a div for that list, and can implement the content in my .js file, while styling it however in my .css file. So here's what I have (and what I'm assuming is all I need) in my html file:
<div class="container">
<div class="row" id="content-list"></div>
</div>
I haven't really touched my css file yet because I like to save the styling for last.
I have a bit of a starting point in my .js file but let me explain a few things before showing my meaningless code (which I wrote based off what I was trying to understand from other examples or tutorials, but didn't fully know what I was doing). All I want, is to display a list of my favorite movies, along with an image aligned next to each movie title. That's all! I don't plan on adding any elements later, or removing... I just want my list but I can't figure it out! I feel so dumb.
Anyway, here's what I have (and yes I'm including the part I had commented out because I'm not sure which way is better, and I apologize for not finishing what I started with):
// JavaScript Document
function myMovies (movieTitle, movieThumb) {
this.movieTitle = movieTitle;
this.movieThumb = movieThumb;
}
/**
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
**/
myMovies.prototype.myMovies = function (list) {
var html =
};
Please help me, I'm so lost. And if you could also please comment any code you give me, that would be so appreciated. Thank you!
Well, you can do this:
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
var htmlStr = ''; // declare a variable which will hold the html for list
for(var i=0;i<contentList.length;i++) // create a loop to loop through contentList
{
htmlStr += "<div><img src='"+contentList[i].img_src+"'/>"+contentList[i].content_title+"</div>";
}
document.getElementById('content-list').innerHTML = htmlStr; // assign the innerhtml
I've commented the code.
LIVE DEMO
By the look of that var html =, I take it you're planning to build up a string of HTML code? I'm gonna assume you have your own plans on how to do that. It's mostly string concatenation, after all.
After you have html ready, use document.getElementById to get a reference to the container and set its innerHTML property to the string you've constructed.
document.getElementById('content-list').innerHTML = html;
In Javascript:
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
var myList = document.createElement("ul"); // create the list
for (var i = 0; i < contentList.length; i++) { // for each Object in your Array
var myItem = document.createElement("li"); // create a item for the list
var myAnchor = document.createElement("a"); // create an anchor for the target_dir property
myAnchor.setAttribute("href", contentList[i].target_dir); // set the href attribute for the anchor
var myTitle = document.createTextNode(contentList[i].content_title); // create the text node to be inside the anchor (from the content_title property)
myAnchor.appendChild(myTitle); // append the text into the anchor
var myImage = document.createElement("img"); // create the DOMElement for the image
myImage.setAttribute("src", contentList[i].img_src); // set the attribute src (from the img_src property)
myImage.setAttribute("alt", contentList[i].content_title); // set the alt attribute only cause it's required for both XHTML and HTML5
myItem.appendChild(myAnchor); // append the anchor into the item list
myItem.appendChild(myImage); // append the image into the item list
myList.appendChild(myItem); // append the item list into the list
}
document.getElementById("content-list").appendChild(myList); // append the list into the div you've created
In jQuery:
var myList = $("<ul>")
for (var i = 0; i < contentList.length; i++) {
var myItem = $("<li>");
var myAnchor = $("<a>").attr("href", contentList[i].target_dir).text(contentList[i].content_title);
var myImage = $("<img>").attr("src", contentList[i].img_src).attr("alt", contentList[i].content_title);
myItem.append(myAnchor).append(myImage);
myList.append(myItem);
}
$("#content-list").append(myList);
In "ugly" (String concatanation) Javascript:
var myHTML = "<ul>";
for (var i = 0; i < contentList.length; i++) {
myHTML += "<li><a href='" + contentList[i].target_dir + "'>" + contentList[i].content_title + "</a><img src='" + contentList[i].img_src + "' alt='" + contentList[i].content_title + "' /></li>";
}
myHTML += "</ul>"
document.getElementById("content-list").innerHTML = myHTML;

Trying to generate table from JSON file with bean tags embedded in HTML

I am trying to generate a table of data from a JSON file using Javascript but am having difficulty because of the bean:write tag. The bean: is getting removed, so only <write name="offenderCountVO" property="addressCount"/> seems to be getting parsed. Is this approach even feasible?
From the page that generates the table:
// Build profile section from JSON file
$.getJSON('<%=request.getContextPath()%>/jsp/json/offenderProfileJSON.jsp', function(data) {
//alert('loading JSON');
var items = [];
var table = $('<table class="profile"><\/table>');
var profileCols = 2;
var td = "";
// Build array of profile categories
for (i = 0; i < data.length; i++) {
//alert("building items");
// Check if this category can be displayed in this module
var item = data[i];
var modules = item["modules"];
//alert("Start check");
if (modules.indexOf(appName) > 0) {
// This category should be displayed
//alert ("Passed");
var label = item["label"];
var link = item["link"];
var name = item["name"];
var property = item["property"];
newCategory = { label: label, modules: modules, link: link, name: name, property: property };
items.push(newCategory);
}
}
// Alphabetically sort categories by label
//alert(items.length);
for (i = 0; i < items.length; i++) {
html = '<tr><td><a href="<%=request.getContextPath()%>/' + items[i].link + '">'
+ items[i].label + '</a></td><td>\u003Cbean\u003Awrite name="'
+ items[i].name + '" property="' + items[i].property + '" /\u003E</td></tr>';
}
$("#testArea").html(html);
//table.appendTo("#testArea");
alert("Done");
}).error(function() {
$("#testArea").html('<span class="error">Error parsing JSON.</span>');
});
The JSON file:
[
{
"label" : "Address",
"modules" : "AGNT,BOOKING,DIO,OMP,OTA",
"link" : "offenderAddress.do?method=list",
"name" : "offenderCountVO",
"property" : "addressCount"
},
{
"label" : "Assessments",
"modules" : "AGNT,BOPP,OMP,OTA",
"link" : "offenderAssessmentList.do?method=list",
"name" : "offenderCountVO",
"property" : "assessmentCount"
}
]
I hope I've explained the issue well enough -- I'm working on several different projects and my head is spinning right now, so let me know if you need any clarification. Any guidance would be appreciated.
<bean:write> is a tag understood by JSP on the server-side, at the point when the initial page is created.
Using:
'<td>\u003Cbean\u003Awrite name="'+ items[i].name + '" property="' + items[i].property + '" /\u003E</td>'
from JavaScript makes no sense because the web browser that includes the resultant <bean:write> tag in its page DOM doesn't know anything about Java or bean tags. When the browser's HTML parser sees <bean:write> it thinks only "that's some write tag that I don't know about, spelled funny" and not "I had better ask the server-side what it's value for the property of that bean is".
If you want the browser to see the server-side value of a variable, you must return that value itself in the JSON response to the browser, not just a name and value pair that only mean anything to the bean-based server side.
Note also that dropping unescaped strings into HTML markup is dangerous. Without HTML-escaping, you have cross-site-scripting security holes when any of the item values may contain user-submitted values. Use DOM-property methods to set element text and attribute values instead of trying to create HTML markup strings from JavaScript. eg:
<input type="hidden" id="contextPath" value="<c:out value="${pageContext.request.contextPath}"/>"/>
...
var cp = document.getElementById('contextPath').value;
for (var i= 0; i<items.length; i++) {
table.append(
$('<tr>').append(
$('<td>').append(
$('<a>', {href: cp+'/'+items[i].link, text: items[i].label})
)
).append(
$('<td>', {text: items[i].value_of_whichever_property_it_is})
)
);
}

Categories