I'm developing a Wikipedia Viewer and I'm trying to extract some data from the Wikipedia API. This is supposed to be a normal request, any idea why this method is not giving any response? I'm using fetch library.
The line console.log(data) doesn't run at all.
function getArticleList() {
var searchFor = "";
searchFor = document.getElementById('intext').value;
console.log(searchFor);
fetch("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchFor + "&limit=5").then(function(resp) {
console.log("trySearch");
return resp.json()
}).then(function(data) {
console.log(data);
document.querySelector.artName.innerText = data.object[1];
document.querySelector.textArt.innerText = data.object[0];
document.querySelector.href = data.object[2]
})
};
From Wikimedia's documentation: 'For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.'
The following worked for me:
fetch("https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=Belgium&limit=5").then(function(resp) {
console.log(resp);
return resp.json()
}).then(function(data) {
console.log(data);
Notice that I filled in my own search with 'Belgium', but your code should work with the right modifications.
Any particular reasons to use fetch library ? This can be done using simple Jquery AJAX.
function getArticleList() {
var searchFor = document.getElementById('intext').value;
var response="";
console.log(searchFor);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=opensearch&search="+searchFor+"&limit=5",
dataType: 'jsonp',
success: function(data){
console.log(data);
response=data;
}
}).done(function(response) {
console.log(response);
document.querySelector.artName.innerText = response.object[1];
document.querySelector.textArt.innerText = response.object[0];
document.querySelector.href = response.object[2];
});
};
Related
I'm working on an ajax call to an API. and upon calling this call, I keep running into this error. Please help. Ive been trying at this for hours and not sure what the issue is. Ive taken out the
JSON.parse and added them back to see if that will help but still no progress.
$.ajax({
type: "POST",
//url: 'http://aeM/api/getDataId',
url: '/bin/soupservice.getDataAccordToId.html',
//async: false,
data: IDschema,
//contentType: "application/json",
beforeSend: function () {
// Show image container
$("#wait").css("display", "block");
},
success:function (data, textStatus, jqXHR) {
console.log(jqXHR.status);
if (JSON.parse(data)) {
let fileDeviceData = [];
let uploadDate = [];
fileDeviceData = data;
let deviceNameFromFileData = [];
$.each(JSON.parse(data), function (i, element) {
dataInFile.push(element.file);
deviceNameFromFileData.push(element.deviceName);
//push an object while interacting with API. used to get similar index locations for later use
duplicateIdCheckedList.push({
"deviceName":element.deviceName,
"lastUploadDate":element.lastUploadDate.split(" ")[0] ,
"fileName": element.deviceName+ " "+element.lastUploadDate.split(" ")[0],
"id":element.id
});
let utcTime = element.lastUploadDate;
let utcText = moment(utcTime).format("L LT");
let anotherway = moment.utc(utcTime).local().format("L LT");
let firstConvertedString = anotherway.split("/").join("-").replace(",", "");
uploadDate.push(firstConvertedString.split(":").join("-").replace(",", ""));
})
//call on the findDuplicateIndex function to organize all the files that will be consolidated together
duplicates=findDuplicateIndex(duplicateIdCheckedList);
valuesforBrowserTime = uploadDate
exportAsTxt(deviceNameFromFileData, valuesforBrowserTime);
}
I see you are requesting a .html file and passing data to JSON.parse that expect a JSON format.
You may need to parse using a different method.
I want to get some data about places using the Google Places API.
Thing is, I want to get data from more than 1000 records, per city of the region I'm looking for.
I'm searching for pizzeria, and I want all the pizzerias in the region I've defined. So I have an array like this:
['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse']
My objective is to make a single request, then wait 3sec(or more), and then process the second request. I'm using Lodash library to help me iterate.
Here is my code:
function formatDetails(artisan){
var latitude = artisan.geometry.location.lat;
var longitude = artisan.geometry.location.lng;
var icon = artisan.icon;
var id = artisan.id;
var name = artisan.name;
var place_id = artisan.place_id;
var reference = artisan.reference;
var types = artisan.types.toString();
$('#details').append('<tr>'+
'<td>'+latitude+'</td>'+
'<td>'+longitude+'</td>'+
'<td>'+icon+'</td>'+
'<td>'+id+'</td>'+
'<td>'+name+'</td>'+
'<td>'+place_id+'</td>'+
'<td>'+reference+'</td>'+
'<td>'+types+'</td>'+
'</tr>');
}
var getData = function(query, value){
$.ajax({
url: query,
type: "GET",
crossDomain: true,
dataType: "json",
success: function(response) {
var artisan = response.results;
console.log(artisan);
for (var i = 0; i < artisan.length; i++){
formatDetails(artisan[i]);
setTimeout(function(){console.log('waiting1');},3000);
}
setTimeout(function(){console.log('waiting2');},3000);
},error: function(xhr, status) {
console.log(status);
},
async: false
});
}
$(document).ready(function(){
var places =
['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse'];
_.forEach(places, function(value, key) {
var proxy = 'https://cors-anywhere.herokuapp.com/';
var target_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+value+'&key=AIzaSyAClTjhWq7aFGKHmUwxlNUVBzFpIKTkOrA';
var query = proxy + target_url;
getData(query, value);
});
});
I've tried a lot of solutions I found on stackoverflow, but no one were working, or I might have done them wrong.
Thanks for your help!
The fact that $.ajax returns a Promise makes this quite simple
Firstly, you want getData to return $.ajax - and also get rid of async:false
var getData = function(query, value) {
return $.ajax({
url: query,
type: "GET",
crossDomain: true,
dataType: "json",
success: function(response) {
var artisan = response.results;
for (var i = 0; i < artisan.length; i++){
formatDetails(artisan[i]);
}
},error: function(xhr, status) {
console.log(status);
}
});
}
Then, you can use Array.reduce iterate through the array, and to chain the requests together, with a 3 second "delay" after each request
Like so:
$(document).ready(function(){
var places = ['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse'];
places.reduce((promise, value) => {
var proxy = 'https://cors-anywhere.herokuapp.com/';
var target_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+value+'&key=AIzaSyAClTjhWq7aFGKHmUwxlNUVBzFpIKTkOrA';
var query = proxy + target_url;
return promise.then(() => getData(query, value))
// return a promise that resolves after three seconds
.then(response => new Promise(resolve => setTimeout(resolve, 3000)));
}, Promise.resolve()) /* start reduce with a resolved promise to start the chain*/
.then(results => {
// all results available here
});
});
The most effective answer is the one above from #jaromandaX.
Nevertheless, I also found a workaround with Google Chrome, which will help you to not get your hands dirty with promises.
On Chrome:
1. Open Console
2. Go to network tab
3. Near the options "preserve log" and "disable cache", you have an option with an arrow where you will see the label "No throttling".
4.Click on the arrow next to the label, then add.
5. You will be able to set a download and upload speed, and most important, delay between each request.
Kaboom, working with my initial code.
Nevertheless, I changed my code to fit the above answer, which is better to do, in terms of code, speed, etc..
Thanks
JQuery Snippet
// THE FOUR URL'S TO ADD THE TOTAL SHARES
var Gal_All = "Link One";
var Gal_S_1 = "Link Two";
var Gal_S_2 = "Link Three";
var Gal_S_3 = "Link Four";
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/' + Gal_All,
success: function(data) {
showCount(data);
}
});
var fbshares;
var fbcomments;
function showCount(responseText) {
var json = responseText;
fbshares = json.shares;
fbcomments = json.comments;
$('#fb-share-count').html(fbshares);
if (fbcomments) {
$('#TotalComments').html(fbcomments + ' comments');
}
showTotal();
}
function showTotal() {
if (!tweets) {
tweets = 0
}
if (!fbshares) {
fbshares = 0
}
if (tweets !== undefined && fbshares !== undefined)
$('#total-share-count').html(tweets + fbshares);
}
For fetching data from one Facebook API I have achieved however my gallery is split up into four pages (Gal_All = all images and Gal_S_1, Gal_S_2, Gal_S_3 = categorized)
Alike I have achieved with my Twitter counter adding for all four pages, I would like to do for Facebook so it is not showing the shares for that page, but all four of the pages.
Please Note: Comments fetch only needs to be from Gal_All
First of all, you can request API data for multiple objects using
/?ids=http://example.com/1,http://example.com/2,http://example.com/3
Now since you want comments as well for your 4th URL, that still needs an extra API request (unless you want to fetch comments for the other three as well, just to throw them away, but that would not make much sense) – but you could use a batch request to at least get those two different API calls done with one single HTTP request. After all, the HTTP request is what takes most of the time in making a request to the API, so if speed is the factor you put the most emphasis on (and why wouldn’t you, users don’t like to be kept waiting), I think this is the best way to go. (Using a promise might be fine from a pure “aesthetic” point of view, but it doesn’t change the fact that multiple HTTP requests are quite slow.)
Use a promise:
var count = 0;
$.when(
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/' + Gal_All,
success: function(data) {
count += data;
}
});
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/' + Gal_S_1,
success: function(data) {
count += data;
}
});
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/' + Gal_S_2,
success: function(data) {
count += data;
}
});
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/' + Gal_S_3,
success: function(data) {
count += data;
}
});
).then(function() {
showCount();
});
I am completely new to SharePoint development.
I am trying to create an app for basic CRUD operation using NAPA.
I took the reference from http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/.
There are some basic get commands in REST.
I am using Get All List Items From a Single List (where url is like: http://UsersrverName/site/_api/web/lists/getbytitle(‘listname’)/items)
Now for getting list items based on ODATA Query, the function is:
function getListItems(url, listname, query, complete, failure) {
// Executing our items via an ajax request
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data); // Returns JSON collection of the results
},
error: function (data) {
failure(data);
}
});
}
here, as per function arguments, I have assigned the value for url and listname, query is blank as I am selecting all items, and I have no idea what to assign for complete and failure.
So my main concern is the arguments to be passed in the function getListItems().
Kindly help. and if there is any other alternative (without using REST), then please suggest.
Basically complete and failure arguments are function callbacks. The following example demonstrates how to call the specified function:
var webUrl = 'http://intranet.contoso.com';
var listTitle = 'Documents';
var queryOptions = '';
getListItems(webUrl,listTitle ,queryOptions,
function(data){ //success callback function
for(var i = 0; i < data.d.results.length; i++){
var item = data.d.results[i];
console.log(item.Title);
}
},
function(error){ //error callback function
console.log(JSON.stringify(error));
}
);
Key points:
SharePoint REST endpoint /_api/web/lists/getbytitle('<list title>')/items returns JSON object in the following format:
(for Documents library)
Another approach that is commonly used and was introduced in jQuery 1.5 is based on the CommonJS Promises/A design:
jQuery.Deferred() provides flexible ways to provide multiple
callbacks, and these callbacks can be invoked regardless of whether
the original callback dispatch has already occurred
The same example that demonstrates how to utilize jQuery.Deferred() object:
function getListItems(url, listname, query) {
return $.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
});
}
Usage
getListItems(_spPageContextInfo.webAbsoluteUrl,'Documents','')
.done(function(data)
{
for(var i = 0; i < data.d.results.length; i++){
var item = data.d.results[i];
console.log(item.Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
I have url http://translate.google.ru/translate_a/t?client=x&text=enter text&sl=en&tl=pl
If you will go through this link in response you will have js file
with text:
{"sentences":[{"trans":"wprowadzania tekstu","orig":"enter text","translit":"","src_translit":""}],"src":"en","server_time":80}
I created ajax request
function GoogleTranslateItem(sourceText, langFrom, langTo) {
$.ajax({
url: 'http://translate.google.ru/translate_a/t',
data: { client: "x", text: sourceText, sl: langFrom, tl: langTo },
dataType: 'jsonp',
jsonpCallback: "getData",
success: function (data) {
alert("Success");
}
});
function getData(data) {
var dataJson = data;
alert('bingo');
}
when the answer comes from server. I can't to process it
in browser shows js error.
Syntax error at line 1 while loading:
{"sentences":[{"trans":"вход вых
------------^
expected ';', got ':'
Linked script compilation
How can i process this response?
I think you should take a look at this (http://javascriptweblog.wordpress.com/2010/11/29/json-and-jsonp/)
var jsonp = {
callbackCounter: 0,
fetch: function(url, callback) {
var fn = 'JSONPCallback_' + this.callbackCounter++;
window[fn] = this.evalJSONP(callback);
url = url.replace('=JSONPCallback', '=' + fn);
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
},
evalJSONP: function(callback) {
return function(data) {
var validJSON = false;
if (typeof data == "string") {
try {validJSON = JSON.parse(data);} catch (e) {
/*invalid JSON*/}
} else {
validJSON = JSON.parse(JSON.stringify(data));
window.console && console.warn(
'response data was not a JSON string');
}
if (validJSON) {
callback(validJSON);
} else {
throw("JSONP call returned invalid or empty JSON");
}
}
}
}
The response from http://translate.google.ru/translate_a/t?client=x&text=entertext&sl=en&tl=pl i JSON, not JSON-P. Accessing JSON-data this way is against the cross-site policies, as the browsers prevent such responses to be returned to the client.
As you are allowed to include scripts from other domains, JSON-P is a way of transfering data as javascript (not JSON). You need to find an API supporting JSON-P (I'm not sure if the Translate API supports JSON-P) or create a proxy on the same domain as your client application to access the JSON data.
Read more about the JSON-P protocol here: http://json-p.org/
To create a proxy, you'll need to implement a service that fetches the content of the Translate API and reprint it in the response.
Example:
/jsonProxy?text=foo
Should return the contents of http://translate.google.ru/translate_a/t?client=x&text=entertext&sl=en&tl=pl
...but you won't have to access it from another domain.
I think the MIME type of the response should be 'application/json'