I can't get Json object attribute - javascript

I'm using JS to do some function in my webpage and I have backend function giving me this JSON
{ "id": 1, "name": "First Like", "description": "Like at least 1 page", "image": "images/badges/FIRST_LIKE"}
So I learned how to get those attributes with jQuery, I can get "name" and "description" but somehow I can't get "image" attribute which I need to add to url to call image href. This is my JS function:
jQuery(function($){
$.getJSON('http://eclipsewildflyserver-gobanit.rhcloud.com/something/id=1',
function (data) {
var name=data.name;
var description=data.description;
var image=data.image;
document.getElementById("name").innerHTML = name.toString();
document.getElementById("description").innerHTML=description.toString();
document.getElementById("image").innerHTML=image.toString();
});
});
It's not giving me any error or something. Just won't get the "image" attribute.

For tag image you need to use src attribute:
document.getElementById("image").src = image;
And you don't need to call toString() function, it's already String
See working example:
var data = { "id": 1, "name": "First Like", "description": "Like at least 1 page", "image": "http://cdn.sstatic.net/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"};
var name=data.name;
var description = data.description;
var image = data.image;
document.getElementById("name").innerHTML = name;
document.getElementById("description").innerHTML = description;
document.getElementById("image").src = image;
<div id="name"></div>
<div id="description"></div>
<image id="image"></image>

Related

Display text from list of variables

I have a series of pages on my site that utilize JavaScript to show a title based on the variable defined in the page.
Basic HTML
<h1 id="pageTitle"></h1>
<script> var page = "start";</script>
<!-- Rest of the page... -->
Separate JavaScript File
var startText = "Hello!";
var middleText = "This is a page";
var endText = "Example";
if(page == 'start'){
$('#pageTitle').html(startText);
}
if(page == 'middle'){
$('#pageTitle').html(middleText);
}
if(page == 'end'){
$('#pageTitle').html(endText);
}
This follows a simple pattern that does the job fine, but can get tedious as the website grows. Is there a cleaner way to get the same result?
Instead of defining a JS variable in every page I suggest to attach a data-* attribute to the title tag like :
<h1 id="pageTitle" data-page="start"></h1>
Then in your separate JS file, you could create an object contains the list of title and use the data-page attributes as a key like :
var titles = {
"start": "Hello!",
"middle": "This is a page",
"end": "Example"
}
var title_element = $("#pageTitle");
var key = title_element.data('page');
title_element.text(titles[key]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="pageTitle" data-page="middle"></h1>
Use an object reference the key...
var messages = {
"foo" : "bar",
"hello" : "world"
}
function setMessage(key) {
document.querySelector("#out").innerHTML = messages[key];
}
setMessage("hello");
<div id="out"></div>
A cleaner way could be to organize the titles in a dictionary.
var titles = {
"start": "Hello!",
"middle": "This is a page",
"end": "Example"
}
$('#pageTitle').html(titles[page]);
It's always a good idea to organize your code into modular functions. This will help keep your code maintainable.
function init(title) {
document.querySelector("#pageTitle").innerHTML = getTitleHtml(title);
}
function getTitleHtml(title) {
const titleMap = {
start: "Hello",
middle: "This is a page",
end: "Example"
};
return titleMap[title];
}
var title = "end";
init(title);
<h1 id="pageTitle"></h1>

How to convert Google PageSpeed Insight JSON results to HTML

I have never worked with JSON before and I am stuck at converting my results to html. I would like them to spit out as ul's and li's preferably. I have tried plugins and Jquery scripts but nothing seems to work. My assumption is that the way I am spitting out the results is incorrect, but as I said I have no idea what I am doing with server response objects.
HTML:
<input type="text" placeholder="Enter webpage URL e.g.http://www.domain.com" id="url"/>
<input type="button" id="button" value="PageSpeed Data" onclick="clicked();" />
<div id="urlerror">Please Enter a Valid URL e.g. http://www.domain.com</div>
<pre id="data"></pre>
My code to get the results:
<script>
function clicked()
{
document.getElementById("urlerror").style.display = 'none';
var xhr = new XMLHttpRequest();
var url = document.getElementById("url").value;
if(url.indexOf('http://') === -1){document.getElementById("urlerror").style.display = 'block'; return;}
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url="+encodeURIComponent(url)+"&key=AIzaSyAIOUFcLYeo2WN1qbPSjlMbXmLi8kmOacw&strategy=mobile");
xhr.onload = function(){
document.getElementById("data").innerHTML = xhr.responseText;
}
xhr.send();
}
</script>
The resulting short snippet JSON object example (not full code):
{
"kind": "pagespeedonline#result",
"id": "http://www.celebritynewsdaily.us/",
"responseCode": 200,
"title": "Celebrity News Daily | Your Daily Source for Celebrity News & Updates",
"score": 64,
"pageStats": {
"numberResources": 71,
"numberHosts": 13,
"totalRequestBytes": "11777",
"numberStaticResources": 35,
"htmlResponseBytes": "235467",
"textResponseBytes": "238",
"cssResponseBytes": "135950",
"imageResponseBytes": "545748",
"javascriptResponseBytes": "762058",
"otherResponseBytes": "107518",
"numberJsResources": 13,
"numberCssResources": 11
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidInterstitials": {
"localizedRuleName": "Avoid app install interstitials that hide content",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your page does not appear to have any app install interstitials that hide a significant amount of content. Learn more about the importance of avoiding the use of app install interstitials.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/webmasters/mobile-sites/mobile-seo/common-mistakes/avoid-interstitials"
}
]
}
}
]
}
}
Any help getting this working is greatly appreciated.
Once you've got the JSON string, it is easy to convert into a JavaScript object by calling JSON.parse().
var myObject = JSON.parse(jsonString);
Once you've got the object, you can reference values within it as per a normal JS object; eg myObject.pageStats.numberResources, and use the DOM methods to insert them into DOM elements.

Get Wikipedia pageid from title

I'm trying to get an image from a Wikipedia article. I have the title of the article but it seems like I need to know the pageid to access the thumbnail. How do I get the pageid from the title?
My JavaScript code:
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&titles=" + article + "&prop=pageimages&format=json&pithumbsize=350", function (data) {
imageURL = data.query.pages[/* pageid */].thumbnail.source;
});
Here's what I'm parsing (example for article = "Car"):
{"query":{"pages":{"13673345":{"pageid":13673345,"ns":0,"title":"Car","thumbnail":{"source":"http://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Benz-velo.jpg/100px-Benz-velo.jpg","width":100,"height":80},"pageimage":"Benz-velo.jpg"}}}}
^ It seems like I first need to know that it's the 13673345 index.
OP asks how to "access the thumbnail", i.e., the URL within the returned data. He did not ask how to access the full image behind the thumbnail ... which is something other answers address.
OP's problem is that the data is keyed to the page ID. In fact, the query could return more than one article in which case there would be multiple page IDs and thumbnails.
The following query returns the data used in the code snippet:
http://en.wikipedia.org/w/api.php?action=query&titles=Stack_Overflow&prop=pageimages&format=json&pithumbsize=350
And OP can extract the page IDs using this code:
var pageid = [];
for( var id in data.query.pages ) {
pageid.push( id );
}
Run the code snippet below to test.
<html>
<body>
<img id="thumbnail"/>
<script type="text/javascript">
var data = {
"query":
{
"normalized": [
{
"from": "Stack_Overflow",
"to": "Stack Overflow"
}],
"pages":
{
"21721040":
{
"pageid": 21721040,
"ns": 0,
"title": "Stack Overflow",
"thumbnail":
{
"source": "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Stack_Overflow_homepage.png/350px-Stack_Overflow_homepage.png",
"width": 350,
"height": 185
},
"pageimage": "Stack_Overflow_homepage.png"
}
}
}
};
// get the page IDs
var pageid = [];
for( var id in data.query.pages ) {
pageid.push( id );
}
// display the thumbnail using a page ID
document.getElementById('thumbnail').src = data.query.pages[ pageid[0] ].thumbnail.source;
</script>
</body>
</html>
Just build your JSON object with JSON.parse so you have an object that looks like:
var response = {
query: {
pages: {
"13673345":{
pageid: 13673345,
ns: 0,
title: "Car",
thumbnail: {
source: "http://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Benz-velo.jpg/100px-Benz-velo.jpg",
width: 100,
height: 80
},
pageimage: "Benz-velo.jpg"
}
}
}
};
And then you can clearly see you don't need pageid in the slightest, you just need to process the correct "pages" object.
In this case there's only one, but even if there would be multiple, just run through Object.keys for the response.query.pages object:
var pages = response.query.pages;
var propertyNames = Object.keys(pages);
propertyNames.forEach(function(propertyName) {
var page = pages[propertyName];
var thumbnail = page.thumbnail.src;
var imgURL = thumbnail.replace("/thumb/",'').replace(/\.(jpg|png).*/,".$1");
doSomethingWith(imgURL);
});
(note the file extension regexp, which we do because who says all images are jpg? Better to pick jpg and png, since those are the two prevailing image formats on the web)

How do I update data embedded in the HTML script tag?

I have a simple html page with Json-ld data embedded in the script tag.
How do I update this data on the submit of a form?
Here is some of the code of the page (data + load function). What I'm missing is the saveData function that updates the data embedded in the script section.
Thank you,
<script id="person" type="application/ld+json">
{
"#context": "http://schema.org",
"#type": "Person",
"givenName": "Marco",
"familyName": "Van Basten"
}
</script>
<script>
function loadData() {
var person = document.getElementById("person").textContent;
var jsonld = JSON.parse(person);
document.getElementById("givenName").value = jsonld.givenName;
document.getElementById("familyName").value = jsonld.familyName;
}
The following code snippet is for example only, but should show you how to update your script object with the JSON string using JSON.stringify.
person.innerHTML = JSON.stringify(jsonld);
Load the original by using Load. Change the values then Save and Load again.
Use the browser developer tools to watch the values of the DOM.
function loadData(e) {
var person = document.getElementById("person");
var jsonld = JSON.parse(person.textContent);
console.log(jsonld.givenName, jsonld);
document.getElementById("givenName").value = jsonld.givenName;
document.getElementById("familyName").value = jsonld.familyName;
}
function saveData(e) {
console.log('event', e);
var person = document.getElementById("person");
var jsonld = JSON.parse(person.textContent);
jsonld.givenName =document.getElementById("givenName").value;
jsonld.familyName =document.getElementById("familyName").value;
//person.innerHTML = JSON.stringify(jsonld);
person.textContent = JSON.stringify(jsonld);
}
document.getElementById("saveButton").addEventListener('click', saveData);
document.getElementById("loadButton").addEventListener('click',loadData);
<script id="person" type="application/ld+json">
{ "#context": "http://schema.org", "#type": "Person", "givenName": "Marco", "familyName": "Van Basten" }
</script>
<form>
<input type="text" id="givenName" />
<input type="text" id="familyName" />
</form>
<button id="loadButton">Load</button>
<button id="saveButton">Save</button>

Passing values php to kinetic js

var data = {
"images": [
"img/image1.jpg",
"img/image2.jpg",
"img/image3.jpg"
],
"captions":[
[
"This is Sample Caption For Image 1",
"Also This is Sample Caption For Image 1"
],
[
"This is Sample Caption For Image 2"
],
[
"This is Sample Caption For Image 3",
"Also This is Sample Caption For Image 3",
"And So Does This !"
]
]
};
var canvasWidth;
var canvasHeight;
var stage;
var layer = new Kinetic.Layer();
function init(config) { }init({"container":"container"});
In above kinetic js Where var data = image:[], caption:[] is use i wanted to use image dynamically which is coming from canvas.php, in canvas.php we have php code and now i have to pass image path and captions to above js
try this :
<script>var img_path = '<?php echo $img_path?>'</script>
use this as a global variable holding your values.
now you can use this variable to your kinetic.js.

Categories

Resources