Wikipedia API - displaying only 4 results - javascript

I'm using the Wikipedia API to display some articles. The only issue is that it only displays the first 4 results. I've looked at similar questions but still can't find a way to display more. Here's the jsfiddle.
JS:
$(document).keypress(function(e) {
if(e.which == 13) {
var searchTerm = $('#searchy').val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&format=json&callback=?";
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function(data){
//console.log(data[1][0]);
//console.log(data[2][0]);
//console.log(data[3][0]);
$('#output').html('');
for (var i = 0; i < data.length; i++) {
$('#output').prepend("<li>" + data[1][0] + "<p>" + data[2][0] + "</p></li>");
$('#centbox').css("top", "14%");
$('#resultati').css("top", "16%");
}
},
error: function(errorMessage){
alert("Error!");
}
})
};
});

You have:
for (var i = 0; i < data.length; i++) {
But data.length is always going to be 4: [0] is the search, [1] is an array of article names, [2] is an array of summaries, and [3] is an array of links.
So perhaps:
for (var i = 0; i < data[1].length; i++) {
$('#output').prepend("<li>" + data[1][i] + "<p>" + data[2][i] + "</p></li>");

Related

TypeError: data.data[i].caption is null Instagram api

$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/self/media/recent/?access_token=",
success: function(data) {
for (var i = 0; i < 20; i++) {
$("#pics").append("<a target='_blank' href='" + data.data[i].link + "'><img src='" + data.data[i].images.low_resolution.url + "'></img></a>");
$("#text").append("<p>"+data.data[i].caption.text+"</p>");
}
}
});
});
am try to get Instagram feed api , the code working fine , but i have error TypeError: data.data[i].caption is null , feed text not show all i get only 3 form 20 element in json .
data json link
If you look at the response, you see that it simply means that there's no caption (for example, look at number 3)
Try something like this:
for (var i = 0; i < 20; i++) {
$("#pics").append("<a target='_blank' href='" + data.data[i].link + "'><img src='" + data.data[i].images.low_resolution.url + "'></img></a>");
if (data.data[i].caption === null) {
$("#text").append("<p>No caption</p>");
} else {
$("#text").append("<p>"+data.data[i].caption.text+"</p>");
}
}
The reason is in some of the caption is null like data[3] ,data[4] in the response. Do a null check before retrieving the text which is inside caption object
for (var i = 0; i < 20; i++) {
if (res.data[i].caption !== null) {
console.log(res.data[i].caption.text);
}
}

Strange javascript (jQuery) behaviour

I have simple chat that uses ajax to get messages, heres the code:
function get_message_chat() {
$.ajaxSetup({
url: "chat.php",
global: true,
type: "GET",
data: "event=get&id=" + mid + "&t=" + (new Date).getTime()
});
$.ajax({
success: function(msg_j) {
if (msg_j.length > 2) {
var obj = JSON.parse(msg_j);
for (var i = 0; i < obj.length; i++) {
console.log(msg_j.length);
if (mid >= obj[i].id) {
continue;
}
mid = obj[i].id;
name = obj[i].name;
msg = obj[i].msg
$("#msg-box ul").append("<li><b><span class=\"username\" >" + name + "</span></b>:<span id=\"msgid_" + mid + "\" class=\"messsage\" style=\"color:black;\" > " + msg + "</span></li>");
if (msg.indexOf('#' + username) != -1) {
$("#msgid_" + mid).css('font-weight', 'bold');
}
}
$("#msg-box").scrollTop(2000);
}
}
});
setTimeout(get_message_chat, 2000);
}
mid = 0;
It grabs messages from php script "starts from mid ID". Then it shows messages to chat(appends to ul) and sets mid to new message id and then loop repeats. The problem is that it stucks fter mid = 9 for some reason. I still have more messages coming:
[{"id":"10","name":"user1","msg":"messages1234"},
{"id":"11","name":"user2","msg":"messages5678"}]
But they wont display. Everyting looks fine, but I can't understand why is that happening. Thank you for all comments.

How to Bind to DropDown using Jsonp response?

Hi i am using jQuery Ajax to bind data to dropdown.I am using arcgis rest services as source.I am able to get response but not able to bind to dropdown.Can anybody help this done.
$.ajax({
url: "url",
data: { f: "json", where: "1 = 1 ", returnGeometry: false },
dataType: "jsonp",
success: function(response) {
console.log( response );
var len = response.length;
$("#ddlDistrict > option").remove();
$('#ddlDistrict').append("<option value='-- Select --'>-- Select --</option>");
for (var i = 0; i < len; i++) {
$('#ddlDistrict').append('<option value="' + response[i].DistrictName + '">' + response[i].DistrictName + '</option>');
}
}
});
My console output is
success: function(response) {
console.log( response, typeof response );
if(typeof response == 'string') {
response = JSON.parse(response);
}
var len = response.features.length;
$("#ddlDistrict > option").remove();
$('#ddlDistrict').append("<option value='-- Select --'>-- Select --</option>");
for (var i = 0; i < len; i++) {
console.log(response.features[i]);
$('#ddlDistrict').append('<option value="' + response.features[i].DistrictName + '">' + response.features[i].DistrictName + '</option>');
}
}
From the response it seems you want to display displayFieldName which has a value of 'DistrictName'
SO you have to pass the key name
for (var i = 0; i < len; i++) {
$('#ddlDistrict').append('<option value="' + response[i].displayFieldName+ '">' + response[i].displayFieldName+ '</option>');
}
Now from response I see displayFieldName is just a key., where as features,fieldAliases,fields are array,object & array of object again.
I am not sure if you want to target fields which have name as key and DistrictName as value. If it is o then loop condition need to be changes
for (var i = 0; i < response.fields.length; i++) {
$('#ddlDistrict').append('<option value="' + response.fields[i].displayFieldName+ '">' + response.fields[i].name+ '</option>');
}

Rest API Multiple Lists in SharePoint

Because SharePoint works async i cannot store the data from multiple lists in array's and access them later.
I need to use 3 lists because they contain data from employees, holidays, and more.
See my code below for more information.
Is there no easier way to work with SharePoint and multiple lists to get the data. I tried also with executequeryasync but i cannot find a working solution for multiple lists. Or to store the value of each list in an array or variable and use it in another function because it's async.
$(function () {
$('#title').html("Inloggen verlofaanvraag");
});
function inLoggen() {
var initialen = $('#initialen').val();
var wachtwoord = $('#wachtwoord').val();
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst werknemers')/Items?$filter=wInitialen eq '" + initialen + "' and wWachtwoord eq '" + wachtwoord + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var werknemers = data.d.results;
for (var i = 0; i < x.length; i++) {
rInitialen = x[i].wInitialen;
rWachtwoord = x[i].wWachtwoord;
rVolledigenaam = x[i].wVolledigenaam;
}
if (i === 0) {
alert("U hebt geen toegang tot deze pagina !");
}
else {
$('#title').html("Welkom " + rVolledigenaam);
$('#inlogform').hide();
persoonlijketellers(werknemers);
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function persoonlijketellers(werknemers) {
var rId = werknemers[0].ID;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
wettelijkeverlofdagen(werknemers, ptellers);
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function wettelijkeverlofdagen(werknemers, ptellers) {
var rId = ptellers[0].ID;
alert(rId);
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
You can store the data from multiple lists in array and access them when all of your async calls are complete, you just need to use some sort of promise pattern.
jQuery's .when method is probably the most useful in a situation like this:
function SPData() {
function getJsonDataAsync(url) {
// returning the $.ajax object is what makes the next part work...
return $.ajax({
url: url,
method: "GET",
contentType: "application/json",
headers: {
accept: "application/json;odata=verbose"
}
});
}
var requestURI1 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI2 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI3 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var req1 = getJsonDataAsync(requestURI1);
var req2 = getJsonDataAsync(requestURI2);
var req3 = getJsonDataAsync(requestURI3);
// now we can do the next line, because req1/2/3 are actually deferreds
// being returned from $.ajax
jQuery.when(req1, req2, req3).done(function(resp1, resp2, resp3) {
/* do something with all of the requests here...
resp1/2/3 correspond to the responses from each call and are each an
array that looks like: [data, statusText, jqXHR], which means that your
data is in resp1[0], resp2[0], etc. */
});
If you want, you can also just assign the returned values to variables in a higher level context, then use individual jQuery deferreds so that you can be sure all of the calls have succeeded before you start working with the data...
...
var x1, x2, x3;
// use the .then(function() { ... }) pattern because we are just returning a
// deferred/promise from $.ajax
getJsonDataAsync(requestURI1).then(function(data) {
x1 = data;
getJsonDataAsync(requestURI2).then(function(data2) {
x2 = data2;
getJsonDataAsync(requestURI3).then(function(data3) {
x3 = data3;
// do something with x1, x2, and x3
});
});
});
}

Parsing the json data from google and twitter differences

I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).

Categories