Get Wikipedia pageid from title - javascript

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)

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>

Error during serialization or deserialization using the JSON JavaScriptSerializer_Unable to fix using previous answers

I know this is a duplicate question but I tried all the previous answers. Not working for me. So I give here my code. When try to load more than 2000 record I got this error.
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength property."
In Controller
public ActionResult Index(SearchFilter sf)
{
Model m = new Model();
IList<Info> Details;
IList<rViewModel> RLst = new List<rViewModel>();
using (var db = new con())
{
RLst = (from p in Details
select new rViewModel
{
Id=p.Id,
Description = p.Description,
Remark = p.Remark,
}).ToList();
m.Result = RLst;
}
return View(m);
}
In View,
$(document).ready(function () {
$('#Product').dataTable({
"columnDefs": [
{ "width": "20%", "targets": 0, "orderable": true, },
{ "width": "40%", "targets": 1,"orderable": true, },
{ "width": "40%", "targets": 2,"orderable": true, },
],"oLanguage": {"sSearch": "Filter:"}
});
var t = $('#Product').DataTable();
t.clear();t.draw();
var model =#Html.Raw(Json.Encode(Model.Result));
if(model!=null && model.length>0 )
{
AddData(model);
}
$('#Id').focus();
});
Result Model is actually a partial view.
On the line in view,
var model =#Html.Raw(Json.Encode(Model.Result));
I got this error. Error image attached below
How to fix?
I tried adding
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
</webServices>
</scripting>
</system.web.extensions>
in web.config already its not working.stuck in this for more than 2 days.. Kindly help..
Thank you mr.Tetsuya Yamamoto for your reference. So far I tried all the link. But as per your link I tried the coding below.
In view
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model.Result);
}
and at the line where I got error,I changed my one
var model =#Html.Raw(Json.Encode(Model.Result));
into the line as below:
var model =#Html.Raw(jsonModel);
Previously also I tried these coding, but wrongly entered in controller. From your link only I find out need to put in view. This will help some one whose web.config declaration is not working.
Link Courtesy(once again) as follows: Json Encode throwing exception json length exceeded
"jsonSerialization maxJsonLength" did not work for me on this problem
But I reference #Halim answer.
This also works for me:
previous code with the problem:
<script>
$(document).ready(function () {
modelname(#Html.Raw(Json.Encode(Model)));
});
</script>
code resolution:
<script>
$(document).ready(function () {
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model);
modelname(jsonModel)
});
</script>

I can't get Json object attribute

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>

Parse content from a html page

Need to dynamically update contents in a div of main page, based on data fetched from other html page
setInterval( function() {
$.ajax({
type:'GET',
url:"url for status",
success : function(data){
console.log(data);
}
})
},3000);
The content of 'data' printed in developer tool console is:
<html>
<style>
</style>
<head>
</head>
<script>
var conns=[{num:1,
id:1,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_1',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
},
{num:2,
id:2,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_2',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
}]
</script>
</html>
Need to extract the ConnectionStatus, Name and ConnectionError from this content and display it in respective div in main page.
I would recommend using a different transfer type, however, you could use something like this:
function break_out_each_id(){//returns array of indexes where id starts
var i = 0;
id_objs = [];
while data.indexOf('id', i) > -1{
id_objs[i] = data.indexOf('id', i);
i++;
}
return id_objs
}
function find_values(){//pseudo code
use the array of indexes from first index to next index
in that string, do index of each value you are looking for (ConnectionStatus...)
then parse that line after the ':' to get the value.
Do this for each index in indexes array
}
Sorry for the pseudo code, but this post is getting really long. Like I said, it would be MUCH better to just send the response as JSON (even if it is a stringified version of it). In that case you could just do a simple JSON.parse() and you'd be done.

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.

Categories

Resources