JavaScript get image from web path - javascript

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>

Related

getJSON - append Images array

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 + '" />');
});
});
});

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>

Microformat oomph.js breaks rest of my JS

I'm writing a little webpage that displays some Flickr photos and also includes microformats using oomph.js. I have bit of JS and when I run the code without <script type='text/javascript' src="oomph.js"></script> the code runs fine (all my photos are loaded. However, when I add in the above script tag, my photos don't load.
Here is my broke JS (doesn't show photos):
<script type='text/javascript' src="jquery-1.6.3.min.js"></script>
<script type='text/javascript' src="oomph.js"></script>
<script>
$(document).ready(function() {
var ajaxURL="http://api.flickr.com/services/feeds/groups_pool.gne?id=626753#N20&lang=en-us&format=json&jsoncallback=?";
$.getJSON(ajaxURL,function(data) {
$('h1').text(data.title);
$.each(data.items,function(i,photo) {
var photoHTML = '<span class="image">';
photoHTML += '<a href="' + photo.link + '">';
photoHTML += '<img src="' + photo.media.m.replace('_m','_s') + '"></a>';
$('#photos').append(photoHTML);
}); // end each
}); // end get JSON
}); // end ready
</script>
and here is the code that works (shows photos):
<script type='text/javascript' src="jquery-1.6.3.min.js"></script>
<script>
$(document).ready(function() {
var ajaxURL="http://api.flickr.com/services/feeds/groups_pool.gne?id=626753#N20&lang=en-us&format=json&jsoncallback=?";
$.getJSON(ajaxURL,function(data) {
$('h1').text(data.title);
$.each(data.items,function(i,photo) {
var photoHTML = '<span class="image">';
photoHTML += '<a href="' + photo.link + '">';
photoHTML += '<img src="' + photo.media.m.replace('_m','_s') + '"></a>';
$('#photos').append(photoHTML);
}); // end each
}); // end get JSON
}); // end ready
</script>
I've browsed the internet and have yet to find a solution. If anyone could shed some light on this issue I would greatly appreciate it :-).
I was able to fix the issue by including an older version of JQuery (version 1.3.2)

My jquery script only works in Firefox, why?

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<div id="div1">dv1</div>
<div id="div2">dv2</div>
<script type="text/javascript">
function getData(){
$.ajax({
type:"GET",
url:"j.json",
dataType:"json",
success: function(jsondata){
output(jsondata);
}
});
}
function output(json){
//var Data = eval('(' + json + ')');
var html = '';
//alert(Data.length);
for(var i=0;i<json.length;i++){
html += ' name:' + json[i].name + ' age:' + json[i].age;
}
document.getElementById('div1').innerHTML = html;
document.getElementById('div2').innerHTML = json[0].name;
}
setTimeout(getData, 3000);
</script>
</body>
</html>
j.json file is
[{"name":"aaa","age":18},{"name":"bbb","age":19}]
The aim of above code is to update div content with data in local json file. I've tried that in IE & Chrome, but neither worked. I've googled a lot but still can't figure it out.
Anyone got any hints? Thanks in advance.
Do you use web server?
AJAX calls doesnt work with URL starting with file://. This because of the same-origin requirements which were instituted to help deal with cross-site scripting (XSS). See here for more details.
And as I noticed, you should use $(document).ready(function(){ your code }) instead of setTimeout(getData, 3000);

Yelp reviews dont display

I am looking at Trying to use jQuery to display JSON text data as an example, but I cannot get any information to display.
When I put the url (http://api.yelp.com/business_review_search?name=pantibar&term=gay&location=Dublin&limit=1&ywsid=XXXXXXXXXXXXXXXXXX) in chrome postman, it does return the information, but I cannot get it to display on my web page.
Any ideas?
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>' + review.text_excerpt + '</p>';
content += '<p>' +review.date + '</p>';
$(content).appendTo('#review');
});
});
}
$(document).ready(function(){
writeScriptTag( "http://api.yelp.com/business_review_search?name=pantibar&term=gay&location=Dublin&limit=1&ywsid=XXXXXXXXXXXXXXXXXX");
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
</head>
<body>
</body>
I added the following to the body and everything worked fine.
<div id="review"></div>

Categories