getJSON - append Images array - javascript

I want to display data from a JSON file through an Ajax request. I display every data value except the array of images. Where am I wrong?
Here is the JSON:
{
"item": {
"name": "ABITO CORTO",
"details": "Maglia leggera, Collo a V, Interno semi-foderato, Logo.",
"composition": "Composizione: 94% Viscosa, 6% Elastam.",
"modelDetails": [
"La modella indossa una taglia 40",
"Misure: 86 - 60 - 90",
"Altezza modella: 178cm"
],
"images": [
"http://cdn.yoox.biz/34/34295573it_12n_f.jpg",
"http://cdn.yoox.biz/34/34295573it_12n_r.jpg",
"http://cdn.yoox.biz/34/34295573it_12n_e.jpg",
"http://cdn.yoox.biz/34/34295573it_12n_d.jpg"
]
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<button id="driver">ONE</button>
<div class="news_details_container">
<img src="" alt="" >
</div>
</body>
</html>
SCRIPT:
$("#driver").click( function() {
$.getJSON( "assets/data/one.json", function(data) {
$.each(data, function(key, value) {
$(".news_details_container").append(value.name);
$(".news_details_container").append(value.details);
$(".news_details_container").append(value.coposition );
$(".news_details_container").append(value.modelDetails);
$(".news_details_container").append('<img src="' + value.images + '" />');
});
});
});
I'm new to Ajax+ JSON. Can anyone help me?
Thanks.

You have a array of img src you need a loop to display all
Try:
$("#driver").click( function() {
$.getJSON( "assets/data/one.json", function(data) {
$.each(data, function(key, value) {
$(".news_details_container").append(value.name);
$(".news_details_container").append(value.details);
$(".news_details_container").append(value.coposition );
$(".news_details_container").append(value.modelDetails);
$.each(value.images, function(i, v) {
$(".news_details_container").append('<img src="' + v+ '" />');
});
});
});
});

You're only returning a single parent object, so you don't need to use each at that point. You do however need to loop over the returned images property. Try this:
$("#driver").click(function() {
$.getJSON("assets/data/one.json", function(data) {
var $container = $(".news_details_container");
$container.append(data.item.name + ' ' + data.item.details + ' ' + data.item.composition + ' ' + data.item.modelDetails.join(' '));
$.each(data.item.images, function(i, url) {
$container.append('<img src="' + url + '" />');
});
});
});

Related

JavaScript get image from web path

My goal is to display a picture from web path. My program automatically gets json formated posts from reddit. Then it takes the path to the image from the response and it looks like this:
https://preview.redd.it/8skueonh6fm21.jpg?auto=webp&s=c189f2a13149d5b3a35b4e84370876e6a8801209
Question is, how can i get the image from that adress? Like .jpg?
Thanks,
You don't even need javascript...
<html>
<img src = "https://preview.redd.it/8skueonh6fm21.jpg?auto=webp&s=c189f2a13149d5b3a35b4e84370876e6a8801209" width="100vw" height= "100vh"/>
</html>
function addUsers(response) {
response.data.forEach((user) => {
$(".user_wrapper").append(
'<div>' +
'<span>' + user.first_name + ' </span>' +
'<img src=' + user.avatar + '>' +
'</div>'
)
})
}
$( document ).ready(function() {
$.get( "https://reqres.in/api/users?page=2",
function( response ) {
addUsers(response)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<div class="user_wrapper"></div>
</body>
</html>

Sign-in with google account on website

I just started using google API, so i feel like i am walking in the dark.
What i want to do:
It is a very common feature. I want my site to have a Google account Sign-In Button using javascipt, and make sure that a given gmail is valid and maybe extract some basic information from the account.
What do i found:
I have followed the instructions from here:
https://developers.google.com/+/web/signin/javascript-flow .
and copied the code in the last steps of the instructions. I have entered my CLIENT_ID that i got when i followed the instructions in the 'tutorial' but my button just doesn't work. I also searched for some examples and are quite different from the code i found in the google site. I feel that i am missing something (actually i think that i am doing something stupid :) ).
And Here is my code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<meta name="google-signin-clientid" content="'MY_CLIENT_ID'.apps.googleusercontent.com" />
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" />
<meta name="google-signin-cookiepolicy" content="single_host_origin" />
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
<script type="text/javascript">
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
function render() {
alert("1");
// Additional params including the callback, the rest of the params will
// come from the page-level configuration.
var additionalParams = {
'callback': signinCallback
};
alert("2");
// Attach a click listener to a button to trigger the flow.
var signinButton = document.getElementById('signinButton');
signinButton.addEventListener('click', function() {
gapi.auth.signIn(additionalParams); // Will use page level configuration
alert("3");
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
</body>
</html>
I have added some alerts, but nothing pops-up and did not used anywhere the 'client secret' password or the JavaScript origins. Also, in the place of 'MY_CLIENT_ID' is actually my client ID.
I don't know if this makes any difference, but my site is not yet on a server. Just working locally (with internet of course!)
Do you know what i got wrong?
Check your console, maybe there are some errors.
Try this example from https://google-developers.appspot.com/+/demos/signin_demo_trigger:
<html>
<head>
<title>Google+ Sign-in button demo: JavaScript flow</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0; width: 600px;}
.hide { display: none;}
.show { display: block;}
</style>
<script type="text/javascript">
var loginFinished = function(authResult) {
if (authResult) {
console.log(authResult);
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// JSON.stringify doesn't work in IE8.
'{<br />' +
' "id_token" : "' + authResult['id_token'] +'",<br />' +
' "access_token" : "' + authResult['access_token'] + '",<br />' +
' "state" : "' + authResult['state'] + '",<br />' +
' "expires_in" : "' + authResult['expires_in'] + '",<br />' +
' "error" : "' + authResult['error'] + '",<br />' +
' "error_description" : "' + authResult['error_description'] + '",<br />' +
' "authUser" : "' + authResult['authuser'] + '",<br />' +
' "status" : {"' + '<br />' +
' "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
' "method" : "' + authResult['status']['method'] + '",<br />' +
' "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
' }<br />' +
'}</code></pre>';
} else {
document.getElementById('oauth2-results').innerHTML =
'Empty authResult';
}
};
function toggleDiv(id) {
var div = document.getElementById(id);
if (div.getAttribute('class') == 'hide') {
div.setAttribute('class', 'show');
} else {
div.setAttribute('class', 'hide');
}
}
var options = {
'callback' : loginFinished,
'approvalprompt' : 'force',
'clientid' : '841077041629.apps.googleusercontent.com',
'requestvisibleactions' : 'http://schema.org/CommentAction http://schema.org/ReviewAction',
'cookiepolicy' : 'single_host_origin'
};
function startFlow(){
toggleDiv('startFlow');
gapi.auth.signIn(options);
}
</script>
<script src="https://apis.google.com/js/client:platform.js" type="text/javascript"></script>
</head>
<body>
<div id="startFlow">
<a class="button button-blue" href="javascript:startFlow();">Click me</a>
to trigger the sign-in flow with
<a href="/+/web/signin/reference#gapi.auth.signIn"
target="_parent"><code>gapi.auth.signIn()</code></a>
</div>
<div id="oauth2-results" class="hide"></div>
<div style="font: 12px sans-serif, Arial; margin-left: 0.5em; margin-top: 0.5em">Reload the example or open in a new window</div>
</body>
</html>
<!-- Sign in with Google+ only work on working website -->
<html lang="en">
<head>
<script src="https://apis.google.com/js/platform.js?onload=renderApp" async defer></script>
</head>
<body>
<div class="g-signin2" id="customBtn">Sign in with Google+</div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
<script>
var renderApp = function() {
// GOOGLE_CLIENT_ID should be create from https://developers.google.com/identity/sign-in/web/devconsole-project
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'GOOGLE_CLIENT_ID.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
});
attachSignin('customBtn'); //Function called for click
});
};
function attachSignin(customBtn) {
auth2.attachClickHandler(customBtn, {}, onSignIn, function(error) {
console.log(JSON.stringify(error, undefined, 2));
});
}
</script>
</body>
</html>

simpleweatherjs js plugin doesnt update new weather temp but instead returns [object object]

Hi I have tried a plugin from simpleweatherjs I followed the samples there and tried to take the geolocation and auto update sample to make a geolocation that automatically updates after a few minutes the script worked fine not until it reached the interval that I have set instead it gives me [Object Object] as a result
here is the script that I have
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="jquery.simpleWeather.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(function(position) {
getWeather(position.coords.latitude+','+position.coords.longitude); //load weather using your lat/lng coordinates
});
});
$(function(){
getWeather();
setInterval(getWeather, 6000);
});
function getWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: 'c',
success: function(weather) {
html = '<h2>'+weather.temp+'°'+weather.units.temp+'</h2>';
html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
html += '<li class="currently">'+weather.currently+'</li></ul>';
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
}
</script>
<div id="weather"></div>
can someone please check my code if what I did was wrong? or am I missing something here? please help me this is driving me crazy
You are calling the getWeather function from the setInterval function, but that function expects two parameters to be passed, which you don't. If you re-arrange your code as follows, it will work:
<script type="text/javascript">
$(document).ready(function() {
getWeather();
setInterval(getWeather, 6000);
});
function getWeather() {
navigator.geolocation.getCurrentPosition(function(position) {
var location = (position.coords.latitude + ',' + position.coords.longitude);
var woeid = undefined;
$.simpleWeather({
location: location,
woeid: woeid,
unit: 'c',
success: function(weather) {
html = '<h2>' + weather.temp + '°' + weather.units.temp + '</h2>';
html += '<ul><li>' + weather.city + ', ' + weather.region + '</li>';
html += '<li class="currently">' + weather.currently + '</li></ul>';
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>' + error + '</p>');
}
});
});
}
</script>
<div id="weather"></div>
You can verify this by going to this JSFiddle: http://jsfiddle.net/wdPA4/

Attempting simple javascript read/print operation against my parse.com database

I'm confused on how to get the javascript to run.
I have a base installation of a parse project on my mac and I have deployed it over and over to my custom parse.com provided sitename.parse.com without error.
I ran "parse new gwhizcloud" which created a simple directory structure. I replaced the index.html with the following content, then ran "parse deploy". So far so good. But when I hit my web site all I get is "User Emails" printed to the web page.
Here are my directory contents that I am publishing
cloud/main.js
config/global.json
public/index.html
All the files are pristine except for index.html which is listed out below
What am I missing?
Also, where do I look to find the console.log output?
Even my "alert" calls below do not seem to fire.
Here is my index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.13.min.js"></script>
<script>
var GWUserObject;
$(document).ready(function() {
Parse.initialize("1U8vTfgwwNSGr<private>y4pawka6x", "Xv3zic5bRl<private>BwhYFqpcpda");
GWUserObject = Parse.Object.extend("User");
console.log( "i feel ready to score!" );
var query = new Parse.Query(GWUserObject);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " of them.");
var s = '';
for(var i=0, len<results.length; i++) {
var result = results[i];
alert(object.id + ' - ' + result.get('email'));
s+= '<p>';
s+= '<b>id:</b> '+ result.objectId + '::';
s+= '<b>Username:</b> '+ result.attributes.username + '::';
s+= 'Email verified: ' + result.attributes.emailVerified + '::';
s+= 'Email: ' + result.attributes.email + '<br/>';
s+= '</p>'
}
$("#list").html(s);
},
error: function(error)
{
alert("Error: " + error.code + " " + error.message);
}
});
});
</script>
<style>
body {
margin-left: 25px;
margin-right: 25px;
font-family: arial;
}
input {
width: 100%;
height: 25px;
}
textarea {
width: 100%;
}
</style>
</head>
<body>
<h2>User Emails</h2>
<div id="list">
</div>
</body>
</html>
Resolved:: Had a syntax error in this line: for(var i=0, len

Can't load friends images with facebook API

I'am following a tutorial from Facebook for making a mobile website application.
But i can't load the images from friends.
I get this:
<img src="[object Object]">
It should work, because i copied the entire code from the example (only changed appId)
Here is the full code:
<html>
<head>
<title>Hello World</title>
<meta name="viewport" content="initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta property="og:title" content="Hello world" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Hello World" />
<meta property="og:description" content="Hello World! This is my mobile web sample app." />
<meta property="og:image" content="http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png"/>
</head>
<body>
<div id="fb-root"></div>
<script>
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: '226909127331855',
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.Event.subscribe('auth.statusChange', handleStatusChange);
};
</script>
<script>
function handleStatusChange(response) {
document.body.className = response.authResponse ? 'connected' : 'not_connected';
if (response.authResponse) {
console.log(response);
updateUserInfo(response);
}
}
</script>
<div id="login">
<p><button onClick="loginUser();">Login</button></p>
</div>
<div id="logout">
<div id="user-info"></div>
<p><button onClick="FB.logout();">Logout</button></p>
</div>
<script>
function loginUser() {
FB.login(function(response) { }, {scope:'email'});
}
</script>
<style>
body.connected #login { display: none; }
body.connected #logout { display: block; }
body.not_connected #login { display: block; }
body.not_connected #logout { display: none; }
</style>
<div id="user-info"></div>
<script>
function updateUserInfo(response) {
FB.api('/me', function(response) {
document.getElementById('user-info').innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
});
}
</script>
Get friends<br>
<div id="user-friends"></div>
<script>
function getUserFriends() {
FB.api('/me/friends&fields=name,picture', function(response) {
console.log('Got friends: ', response);
if (!response.error) {
var markup = '';
var friends = response.data;
for (var i=0; i < friends.length && i < 25; i++) {
var friend = friends[i];
markup += '<img src="' + friend.picture + '"> ' + friend.name + '<br>';
}
document.getElementById('user-friends').innerHTML = markup;
}
});
}
</script>
Publish feed story<br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'I\'m building a social mobile web app!',
caption: 'This web app is going to be awesome.',
description: 'Check out Facebook\'s developer site to start building.',
link: 'http://www.facebookmobileweb.com/hello',
picture: 'http://www.facebookmobileweb.com/hackbook/img/facebook_icon_large.png'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>
Send request<br>
<script>
function sendRequest() {
FB.ui({
method: 'apprequests',
message: 'invites you to learn how to make your mobile web app social',
},
function(response) {
console.log('sendRequest response: ', response);
});
}
</script>
<fb:like></fb:like>
</body>
</html>
Here is the tutorial: https://developers.facebook.com/docs/mobile/web/build/
Try changing your code to this:
'<img src="' + friend.picture.data.url + '"> '
As #Gyan mentioned, take a look at the open graph explorer to see what the underlying data structure looks like.
you are doing only a bit wrong
go for this link face book developer tool for graph api for freindlist link
you will get friends something like
{
"name": "Nishant Porwal",
"id": "522901714",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/372008_522901714_1470071180_q.jpg",
"is_silhouette": false
}
}
}
and now see your code
'<img src="' + friend.picture + '"> '
you have to parse
you defently find that you are placing an object instead of placing url so change your code and get url because src always work for image url :) might i am given you an idea where you are wrong
change it to
'<img src="' + friend.picture.data.url + '"> '
General advice is to check the object type returned by your method. Since you are being returned an object, there is likely a property like image you can reference from that object... something like objectName.imageURI

Categories