MediaWiki has a url that directs to the full image url.
<img src=
"https://www.mediawiki.org/wiki/Special:FilePath/Wikimedia_Hackathon_Prague_2019_-_Group_Photo_-_CLK_-_cropped.jpg"/>
However, the issue with using this path is that sometimes the image will fail to load. My guess is that the url is going through several redirects to fetch the actual image's url. This especially becomes more problematic if you're trying to load multiple images at the same. As such, I'm trying to see if I can retrieve the final path of the Special:FilePath url using ajax.
$.ajax({
url:
"https://www.mediawiki.org/wiki/Special:FilePath/Wikimedia_Hackathon_Prague_2019_-_Group_Photo_-_CLK_-_cropped.jpg",
type: "GET",
success: function (data) {
console.log(data);
}
});
However, this never even reaches success, so I'm not certain what needs to happen.
If you want to use AJAX, try MediaWiki API (manual):
Generic JavaScript:
var api = "https://en.wikipedia.org/w/api.php";
var params = {
action: "query",
format: "json",
prop: "imageinfo",
iiprop: "url",
titles: "File:Wikimedia Hackathon Prague 2019 - Group Photo - CLK - cropped.jpg"
};
api = api + "?origin=*";
Object.keys(params).forEach(function(key){api += "&" + key + "=" + params[key];});
fetch(api)
.then(function(response){return response.json();})
.then(function(response) {
var pages = response.query.pages;
for (var p in pages) {
console.log(pages[p].title + " is at: " + pages[p].imageinfo[0].url);
}
})
.catch(function(error){console.log(error);});
In MediaWiki environment:
var params = {
action: 'query',
format: 'json',
prop: 'imageinfo',
iiprop: 'url',
titles: 'File:Wikimedia Hackathon Prague 2019 - Group Photo - CLK - cropped.jpg'
},
api = new mw.Api();
api.get( params ).done( function ( data ) {
var pages = data.query.pages,
p;
for ( p in pages ) {
console.log( pages[p].title + ' is at: ' + pages[p].imageinfo[0].url );
}
});
Related
I'm catching data from Database with Ajax.
In the second Ajax request I try to put the variables from first Ajax request to the new DOM elements from second request but there the variables have same value from last array possition.
I have no idea why .
unfortunately I didn't find the information about that.
a simple example:
//Firt ajax request
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "connect/get-fistinformations.php",
data: {
folder_type:folder_type
},
dataType: "json",
for(var first_key in json){
var info = json[first_key];
//If I put there some alert - alert('some_alert'); - the rest of the code works fine
//Catching Data with Json - working correctly
var folder_id = info[0];
var folder_name = info[1];
var folder_date = info[2];
folder_id;
//Second ajax request
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: 'connect/get-secondinformations.php',
data: {
folder_type:folder_type,
folder_id:folder_id
},
dataType: 'json',
success: function(json){
for(var s_key in json){
var second_info = json[s_key];
//Catching more data from other Data table - working correclty
var count = second_info[0];
var route = second_info[1];
var distance = second_info[2];
var price = second_info[3];
var price_per_km = +(price) / (+(route) + +(distance));
//Without the alert from the firt ajax request
//There inside new elements I try to put variable from first Ajax catching (folder_id, folder_name,folder_date)
//But every time when I add new elemets to DOM, these three variables have same value - from last arrray position
//For example folder_id = '50' | folder_name = 'Some folder name' | folder_date = '2020-07-04'
//New elements for DOM
if(count>0){
var full_line_folder = '<div class="full-line-folder folder">'+
'<i class="some-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono: '+folder_date+'<br />Pozycje: '+count+'<br />Dystans: '+route+'km<br />Stawka: '+price_per_km+' €/km<br />Puste kilometry: '+distance+'km</span>'+
'<input type="radio" name="folderid" value="'+folder_id+'" style="display:none;" checked/>'+
'</div>';
$(full_line_folder).appendTo(point);
}else{
var empty_line_folder = '<div class="empty-line-folder folder">'+
'<i class="empty-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono:'+folder_date+'<br />Pozycje: 0<br />Dystans: 0km<br />Stawka: 0 €/km<br />Puste kilometry: 0km</span>'+
'<input type="radio" name="folderid" value="'+folder_id +'" style="display:none;" checked/>'+
'</div>';
$(empty_line_folder).appendTo(point);
}
}
},
error: function(note){
alert('error');
}
});
}
},
error: function(note){
alert('error');
}
});
The problem is that your first loop proceeds to the next iteration before the data arrives for the ajax request it makes. Mostly, by the time your first ajax response arrives, the loop is already gone and any external variables you try access will have their last values.
There are many workarounds for this. I don't think discussion all that is the scope of this answer.
Your options:
Use closures correctly.
Serialize the requests by using async/await
As a starter in html world, i would like to know and start using simple APIs to insert into my blog posts.
I tried to include as html values some simple API like: https://bitcoinfees.earn.com/api/v1/fees/recommended and I used examples given here: Display Json data in HTML table using javascript and some others more like: http://jsfiddle.net/sEwM6/258/
$.ajax({
url: '/echo/json/', //Change this path to your JSON file.
type: "post",
dataType: "json",
//Remove the "data" attribute, relevant to this example, but isn't necessary in deployment.
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
function drawTable(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(drawRow(data[i]));
}
$("#personDataTable").append(rows);
}
function drawRow(rowData) {
var row = $("<tr />")
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
return row;
}
but the result is always blank.
Please, can you give me some hint to can use that API and insert that numbers values for "fastestFee","halfHourFee","hourFee" as html values?
Thank you all!
Welcome to the html world. You are certainly right in assuming that data from APIs is a great way to make your websites more dynamic.
There is an example on W3 Schools on how to handle a http request. I think this is a good place to start https://www.w3schools.com/xml/xml_http.asp. You create a http object that does some sort of data fetching. In this example it is done with the xhttp.send(). At the same time you have a listener that monitors if the onreadystatechange property of the xhttp has changed. And if that change is status 200 (success) then perform some actions.
Here is my JSfiddle with example from your API
http://jsfiddle.net/zvqr6cxp/
Typically these actions would be to structure the returned data and then do something with the data, like show them in a table.
The example shows the native html xhttp object in use with an event listener. Typically as you learn more about this you would probably start using a framework such as jquery or Angular that can handle http requests smoother, keyword here is callback functions.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//In this example, I used your API link..first I would do is turn the JSON into a JS object
myObject = JSON.parse(xhttp.responseText)
document.getElementById("fast").innerHTML = myObject.fastestFee
document.getElementById("half").innerHTML = myObject.halfHourFee
document.getElementById("hour").innerHTML = myObject.hourFee
}
};
xhttp.open("GET", "https://bitcoinfees.earn.com/api/v1/fees/recommended", true);
xhttp.send();
Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});
I've have a JSON file in my local machine with several property listings in it.
A snippet of the code is as follows for reference;
{
"properties": [
{
"id":"prop1",
"type":"House",
"bedrooms":3,
"price":650000,
"tenure":"Freehold",
"description":"something something etc...",
"location":"Petts Wood Road, Petts Wood, Orpington",
"picture":"images/prop1pic1small.jpg",
"url":"prop1.html",
"added": {
"month":"January",
"day":12,
"year":2016
}
}
}
Then I've written a script in AJAX that allows me to retrieve contents from the JSON file based on different attributes.
btnType.addEventListener('click', function() { //search by house type
var searchText = document.getElementById("search").value;
$.ajax ({
url: 'properties.json',
dataType: 'json',
type: 'get',
cache: 'false',
success: function(data) {
var noResults = 0; // this variable is used to capture if no results are returned
var output = '<ul>'; //the final output is concatenated to one variable to be displayed
var len = data.properties.length;
for (i=0; i < len; i++) { //condition is checked with the JSON data and returns only the valid results
if (data.properties[i].type == searchText) {
output += '<section id = "oneResult">';
output += '<p id = "resultID">Property Code: ' + data.properties[i].id + '</p>';
output += '<img src = "'+data.properties[i].picture+'">';
output += '<p id = "resltDesc">'+data.properties[i].description+'</p> See More <br>';
output += '<p>Going for $'+data.properties[i].price+'</p> <br>';
output += '</section><br><br>';
noResults++;
}
}
output += '</ul>';
$('#update').html(output); //final output displayed
if (noResults == 0) {
$('#update').html("No results found");
}
}
});
});
The thing I wanted to know is when I run this on Google Chrome(the most commonly used browser), the results do not appear and the the developer console shows the following error;
XMLHttpRequest cannot load file:///D:/IIT/LVL5%20SEM1/Adv.%20Client%20side%20Web/FINAL%20CW/FINAL%20FILES/2015235-w1608508-CW2-ACWD/properties.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
But the exact same file when I run it on Firefox runs without an hiccups.
Is this something to do with my code or something more browser specific?
EDIT - Since this is a browser specific security feature by the looks of it, it's even more intriguing now to know to what issues does it provide security to?
What I assume you get is an Access-Control-Allow-Origin. This is a security feature in chrome, but luckily it can be disabled. You have to start chrome with disable-web-security, which can be done on windows as follows,
chrome.exe --disable-web-security
Refer this for more information (Answer is also based on this).
As a noob, I'm trying to parse a weather.com RSS feed for display on my site. The code below successfully retrieves the data and displays it as an alert. My question is how to take this further and parse the resulting feed instead of just displaying it? The goal is to take parts of the response and embed it into the HTML on the page. For example, if I wanted to output a table that has a row with the current temperature, what would be the syntax?
<script>
function parseRSS(url, callback) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
parseRSS('http://rss.weather.com/weather/rss/local/USAK0012?cm_ven=LWO&cm_cat=rss&par=LWO_rss',
function(json)
{
alert("Result: " + JSON.stringify(json));
});
</script>
If it helps anyone, here is how I ended up doing it. I went with the feed from accuweather.com, instead of weather.com, just because I happened to get it working first.
1) Obtained the value of the feed "title" field, which contained the current weather values that I needed.
var weatherFeed = json;
var currentConditions = weatherFeed.entries[0].title;
2) Extracted the specific elements, for example currentTemperature:
var firstColonIndex = currentConditions.indexOf(":");
var secondColonIndex = currentConditions.indexOf(":", firstColonIndex + 1);
var currentTemperature = currentConditions.substring(secondColonIndex + 1);
3) Built the HTML using jQuery and embedded the extracted weather values, then put the whole thing within a Div element on my page:
<div class="tile-content" id="MyCityWeather">
<script type="text/javascript">
var weatherElement = "#MyCityWeather";
var temperatureElement = $("<h2/>",
{
style: "margin-left: 25px!important; font-size: 46px!important;"
});
temperatureElement.append(currentTemperature);
temperatureElement.appendTo(weatherElement);
</script>
</div>