Display Images from JSON Array using JavaScript - javascript

I tried to display an image from the image folder in JSON array to Javascript but I am not sure if I am getting the right path.
When the click event happens, everything works except for the image is not showing in the <img id "picture">, the picture is not showing up in the img section of my HTML.
I tried to change the path to ../Images/room_1.jpg but it still not working.
FYI: I have a separate folder that stores images, both json and js are stored in the javascript folder. should I put the same image file in the javascript folder?
html
<h2>Select a Hotel</h2>
<ul class ="hotels">
<li> Marriott Hotel Rooms</li>
</ul>
<h2 id="hotelName">Hotel</h2>
<h3>Adress: <span id="address"></span></h3>
<img id="picture">
Hotel.json
{
"hotels": [
{
"name": "Marriott",
"address": "098 hollywood Street",
"picture": "room_1.jpg"
}
JS
async function getHotelData() {
try {
const response = await fetch('Javascript//hotel.json')
return await response.json()
} catch (error) {
console.error(error)
}
}
let hotelData = {}
getHotelData().then(data => hotelData = data)
const hotelEvent = document.querySelectorAll("a").forEach(a => {
a.addEventListener('click', hotelInfo )
})
function hotelInfo(event) {
let hotelChoice = hotelData.hotels.find(hotel => {
return event.target.id === hotel.name.toLowerCase()
return event.target.id === hotel.address.toLowerCase()
return event.target.id === hotel.picture.toLowerCase()
})
console.log(hotelChoice)
document.querySelector("#hotelName").textContent = `${hotelChoice.name} Hotel`
document.querySelector("#address").textContent = `${hotelChoice.address}`
document.querySelector("#picture").innerHTML = `${hotelChoice.picture}`
}

You need to set the src property to the image instead of setting its innerHTML.
A normal img tag would look something like this:
<img id="image" src="/path/to/image.png">
You need to replicate the same using JavaScript:
document.querySelector("#picture").innerHTML = `${hotelChoice.picture}`
// Becomes
document.querySelector("#picture").src = `${hotelChoice.picture}`
Also, pay attention to the image path inside the JSON file, it should be relative to the HTML document you're using it, not the JavaScript one. So if your images are stored inside a separate directory you should change the path inside your JSON file accordingly.
Example:
If your HTML file is in the project root and there is an images folder, you JSON should be something like:
{
"hotels": [
{
"name": "Something",
"address": "Some Street, 12",
"picture": "images/picture_name.jpg"
}
]
}

Related

Angular - Use a default image if image does not exist on server

I have a component that will display a cover image. The user can upload a cover image and the component will display the user uploaded image. If the user doesn't upload an image, then I want to display a default image.
If there is no user uploaded image I want to return an error and call the changeSource(event), which should in theory bind a new image url to the img src. However I'm getting undefined for the event.target.src and I'm seeing a blank space where the default image should be. It works fine when displaying the custom image.
component.html
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{coverPhoto}}"
(error) ="changeSource($event)" />
</div>
component.ts
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
changeSource(event) {
event.target.src = "https://imageurl";
}
directly use (where defaultImage is a variable in ts file which holds the default image path) -
(error)="$event.target.src = defaultImage"
your HTML -
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{ coverPhoto }}" (error)="$event.target.src = defaultImage" />
</div>
Working example here.
You are passing event from this code in ts, which is obviously undefined, and you don't need to call this function from here -
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
The *ngFor was throwing it off. Removing this seemed to solve the problem. Not quite sure why so will post an edit when I discover why.
<div>
<img src="{{coverPhotos}}"
(error)="$event.target.src = defaultImage" />
</div>

How to pass html content in zendesk using node-zendesk

I using node-zendesk package to create ticket on zendesk platform. It has created the ticket successfully on the zendesk platfrom. But unable to send the html content through below code. So how to pass the html content on the zendesk api.
var ticket = {
"ticket":
{
"subject":subject,
"comment": {
"body": "<p>Hello</p>"
}
}
};
client.tickets.create(ticket, (err, req, result)=> {
if (err) {
console.log('client.tickets.create-err', err);
return;
}
})
i had the same issue, you can use markdown syntax to do different stuff for example text(one * before and after text) text (two * before and after text) text (three * before and after text).
Or to do different stuff try to edit the text using markdown before assign it to body.
If you want to pass HTML into the ticket body don't use "body" instead use "html_body", then your HTML will be parsed like this:
"ticket":
{
"subject":subject,
"comment": {
"html_body": "<p>Hello</p>"
}
}

ReactJS Dynamic Anchor tag href rendering based on csv file Undefined

I'm using React and React-DOM inline to make a dynamic filter gallery for showcasing projects of my contributors.I have parsed a CSV file that contains the names of the different contributors, the category based on which the tiles will be sorted (project categories) and the URL to each project this is stored in data variable.
for(var i=0;i<data.length;i++) {
var photo = {
id: i,
category: data[i].Style,
pageurl: "./explore/" + data[i].name.toLowerCase().replace(/ /g, "-") + ".html" ,
//iu: "./explore/" + String(data[i].name) ,
imageUrl: "./explore/" + String(data[i].image_path)
};
PHOTODATA.push(photo);
}
When I log this PHOTODATA variable the DOM shows the different URLs correctly as expected, like this.
0: {id: 0, category: "Futurism", pageurl: "./explore/steely-dan.html", imageUrl: "./explore/thumbnail.jpg"}
This is the piece of code where I render the div and the <a> tag using React
var Photo = React.createClass({
render: function(){
return (
<a className = "photo-container" href= {"./explore/"+ String(this.props.pageurl)} >
<div data-category={this.props.category} >
<img src={this.props.imageUrl} />
</div>
</a>
);
}
And this is how the rendered tag looks in the DOM.
<a class="photo-container" href="./explore/undefined.html" data-reactid=".0.1.$0"><div data-category="Futurism" data-reactid=".0.1.$0.0"><img src="./explore/thumbnail.jpg" data-reactid=".0.1.$0.0.0"></div></a>
I'm puzzled by how the URL comes out as undefined while when I try something like {"https://www.google.com"} then it renders it correctly. Only the dynamic rendering seems to have a problem. I've also tried changing the names of the variables but the issue still persists. Either the DOM doesn't render the href of it renders it as undefined.
How can I fix this issue to link each divs to their own custom html page defined by the CSV file?

Image Gallery hosted in Google Drive Folder

I've been looking for a way to create a gallery on a website with images from a folder in my google drive. Which I have shared here: https://drive.google.com/drive/u/0/folders/0Bwx-OwnNeIvwRldSVlU5SGN0dGs
inside it is a simple HTML, and a gallery folder with pictures of monster trucks and cute animals. And the goal is here to create a gallery where people can upload images of well; monster trucks and cute animals.
I've been searching for all kinds of methods of achieving this and this is what I have found so far:
In short what I am trying to achieve is to get the id's of images in a publicly shared folder in my G-Drive. Then use those id's to create a gallery via JS in an HTML.
What my HTML looks like now:
index.html
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<!-- all divs will append here -->
</div>
What I researched on the Drive SDK:
I've been using the "try it" section here to figure out what i need to do. https://developers.google.com/drive/v2/reference/children/list#examples
Request result: GET https://www.googleapis.com/drive/v2/files/0Bwx-OwnNeIvwRG5rNzZ6OURSNEk/children?fields=items%2Fid
Response result:
200 OK
- SHOW HEADERS -
{
"items": [
{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
},
{
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
},
{
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
},
{
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
},
{
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
},
{
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]}
What I would like for the script to do:
script.js
var imageIds = <!-- ids from the the response --> ;
var x = imageIds.length;
for (var i = 0; i < x; i++) {
<!-- create a <div> -->
}
//See below*
Create a div: In the for loop it will create a <div> with a specific "class" and an <img> inside that div, with a "src="http://drive.google.com/uc?export=view&id=IMAGE-ID" where the "IMAGE-ID" was gotten from the "Response". the <div> will then be appended to <div id="gallery"> in the index.html.
What I would like for the end HTML do look like:
index.html:
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwaFZXVzVmMl9ILUU">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwVk1DTEpnR0J6VHc">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwblBHLVEza0hxY2s">
</div>
<!-- and so on ... -->
</div>
What I am unsure of now, is how this needs to be authenticated to get the image-ids from the G-Drive folder. This could be hosted from Google Drive itself with their hosting links, or it could be created through Google Apps Script, and the functionality to serve HTML there, and that would make the authentication easier as you can get everything from drive directly.
I don't understand why this is no where to be found, that does not involve a payment. It would be great if everyone had the opportunity to create image galleries from images in a G-Drive folder.
Would really like your help on this one. Thanks alot.
Firstly, about the code itself, it would be something like that:
document.addEventListener('DOMContentLoaded', function() {
var response = {
"items": [{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
}, {
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
}, {
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
}, {
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
}, {
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
}, {
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]
};
var imageIds = response.items.map(function(item) {
return '<div class="brick"><img src="http://drive.google.com/uc?export=view&id=' + item.id + '"></div>';
});
document.getElementById('gallery').insertAdjacentHTML('afterbegin', imageIds.join(''));
});
<div id="gallery"></div>
About the authorization, take a look at their documentation.

Use AJAX to load content to a jQuery UI dialog

On my site, I have a bunch of profile previews that are being generated by running JSON data through a mustache.js template.
Here's the template:
<script id="profile-preview-template" type="text/template">
<div class="col-sm-3">
<a style="display:block">
<div class="profile-preview">
<img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
<h1>{{first_name}} {{last_name}}</h1>
<h2 class="text-muted">{{major}}</h2>
<h3 class="text-muted">Cohort {{cohort}}</h3>
</div>
</a>
</div>
</script>
The profile preview shows select info from the JSON info like first_name, last_name, etc.
Here's the format of the JSON data:
{
"profiles": [
{
"first_name": "Robert",
"last_name": "Hosking",
"img_url": "img/about/hackbert.jpg",
"major": "Computer Science",
"cohort": 12,
"bio": "some info",
"linkedin": "some url",
"home_town": "some place",
"status": "Student"
},
{
"first_name": "Jimmy",
"last_name": "Harval",
"img_url": "img/about/hackbert.jpg",
"major": "Chemistry",
"cohort": 13,
"bio": "some info",
"linkedin": "some url",
"home_town": "some place",
"status": "Student"
}
]
}
However, when one of the previews is clicked, I'd like to make a jQuery UI dialog modal popup containing all of the info in the JSON data (not just the data displayed in the preview).
My question is how do I get a reference as to which profile preview was clicked so I know where in the JSON file to look to get the rest of the information.
I made some slight changes to your HTML and template script.
<div class="profile-full"></div>
<div class="preview"></div>
<script id="profile-preview-template" type="text/template">
<div class="col-sm-3">
<a style="display:block">
<div class="profile-preview">
{{#profiles}}
<img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
<h1 id="whichProfile">{{first_name}} {{last_name}}</h1>
<h2 class="text-muted">{{major}}</h2>
<h3 class="text-muted">Cohort {{cohort}}</h3>
{{/profiles}}
</div>
</a>
</div>
</script>
As you can see, 2 divs for demonstration purposes.
.profile-full Where the contents of the correct object is output using JSON stringify. What gets output can of course be changed, this is just to show that the correct object is selected.
.preview Where the preview profiles are generated.
I also added the opening and closing {{#profiles}} {{/profiles}}
profile is derived from what is set in the beginning of your json.
"profiles": [
We assume that you have correctly linked the jQuery and mustache.js libraries. Name your json file from your post as data.json
You must also link the .js file below. I have named it main.js.
$(function() {
$.getJSON('data.json', function(data) {
var template = $('#profile-preview-template').html();
var html = Mustache.to_html(template, data);
$('.preview').html(html);
allProfiles = data.profiles;
lookup = [];
for(i=0;i<data.profiles.length;i++) {
lookup.push(data.profiles[i].last_name);
};
});//getJSON
$(document).on('click', '#whichProfile', function() {
var whichName = $(this).text().substr($(this).text().indexOf(" ") + 1);
var i = jQuery.inArray(whichName, lookup);
$('.profile-full').html(JSON.stringify(allProfiles[i]));
});
});//document ready
So what's happening here?
$(function() {
$.getJSON('data.json', function(data) {
var template = $('#profile-preview-template').html();
var html = Mustache.to_html(template, data);
$('.preview').html(html);
After our document.ready shorthand, we GET the contents of the data.json, and hold it in data. Then we put the contents of html into the div with a class of preview, as we have formatted it according to the template script.
allProfiles = data.profiles;
lookup = [];
for(i=0;i<data.profiles.length;i++) {
lookup.push(data.profiles[i].last_name);
};
});//getJSON
Next we'll create an array called lookup which contains only the last_name data from our json. This will make it possible and fast to get the reference as to which profile preview was clicked.
If you only have a few names, using the last name is fine, but use a unique identifier if the amount of profiles grows (So overlapping last names doesn't occur). Consider adding a unique id, or email to your json.data.
Then close your getJSON.
$(document).on('click', '#whichProfile', function() {
var whichName = $(this).text().substr($(this).text().indexOf(" ") + 1);
var i = jQuery.inArray(whichName, lookup);
$('.profile-full').html(JSON.stringify(allProfiles[i]));
});
});//document ready
Here on clicking a name will get the .text of what's on our page. We will convert it so it's only the last name (strip everything before the space).
We then search for this last name within the lookup array and return its index. Now that we have this index we can use it to get any value within the json relative to the index. In this example we just put the entire stringified contents of the relevant object into our profile-full div
Finally we close our document.ready.
Try clicking on a name (Can be the first or last name). We could of course put anything from that relevant object anywhere else. For example:
remove the line
$('.profile-full').html(JSON.stringify(allProfiles[i]));
and replace it with
alert(allProfiles[i].first_name + ' ' + allProfiles[i].last_name +
' is studying ' + allProfiles[i].major + ' as their Major');
Now clicking on a name will get a pop up, stating their full name and which Major they are studying.
In your template, give each <a> element an id attribute equal to the index of the corresponding profile in the JSON array.
Then, you can give the <a> element an onclick method such as foo(this), because this will pass the element to the function. In your function, you can retrieve the id with $(elem).attr("id"), where elem is the function parameter. Now you have the index of the profile, so it should be easy to retrieve the profile's information.

Categories