Using Wikipedia's API to fetch results from search query - javascript

I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :
"use strict";
$(document).ready(function(){
function searchWikipedia(searchCriteria){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);
}
$('#btn').click(function searchCriteria() {
var searchCriteria = $("input[name=Wikipedia]").val();
searchWikipedia(searchCriteria);
})
function processResult(apiResult){
if (apiResult.query.pages[-1]){
console.log("No results");
} else {
for (var i = 0; i < apiResult.length; i++){
$('#display-result').append('<p>'+apiResult+'</p>');
}
}
}
});
So far nothing appends to my html and there's no errors in my console.

#Ali Mamedov's answer is the way to go (it's from Wikipedia)
But the wikipedia link is missing the http:. Also, you can handle the response on your function:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: processResult
});
});
});
function processResult(apiResult){
for (var i = 0; i < apiResult.query.search.length; i++){
$('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
}
}

<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, item) {
if (i == 1) {
var searchData = item[0];
WikipediaAPIGetContent(searchData);
}
});
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
function WikipediaAPIGetContent(search) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=" + search + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
// remove links as they will not work
blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });
// remove any references
blurb.find('sup').remove();
// remove cite error
blurb.find('.mw-ext-cite-error').remove();
$('#results').html($(blurb).find('p'));
$('#results').html(blurb);
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
</script>

Try this sample:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: function (x) {
console.log('title', x.query.search[0].title);
}
});
});
});
Source

This will show the query result with image:
$(document).ready(function(){
$('#btn').click(function() {
var search_text = $("input[name=Wikipedia]").val();
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
$.getJSON( url + search_text +'&callback=?',function(data){
for(var key in data.query.pages){
var titleArt = data.query.pages[key].title;
var extractArt = data.query.pages[key].extract;
var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
var imgArt;
if(data.query.pages[key].hasOwnProperty('thumbnail')){
imgArt = data.query.pages[key].thumbnail.source;
} else {
imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
}
var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></div></div>';
$('#display-result').append(contentHTML);
}
});
});
});

function Wiki(lang) {
this.lang = lang || "fr";
this.inuse = false;
}
Wiki.prototype.research = function(s, callback) {
if (this.inuse) {
console.error("Wiki est déjà en cours d'utilisation !");
} else {
this.inuse = true;
var r = new XMLHttpRequest();
r.onload = function() {
Wiki.prototype.inuse = false;
var j = JSON.parse(r.responseText);
callback(j);
}
r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
r.send();
}
}
var c = new Wiki();
c.research("Victor Hugo", function(result) {
console.log(result);
});
//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
console.log(result);
}

Related

The Function App/GetSPANList returns 401 error on server. C# asp.net

The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}

Save value in dropdown using javascript

I want to set default values in nested dropdowns of Country > State > City > Zone # the time of form editing.
All data are filled in all dropdowns but the value is not set.
I have used select2 dropdown and filling data using jquery ajax in asp.net form.
=======================================================================
function Edit()
{
$(response.d).find("tblInvoice").each(function () {
selCountryId = $(this).find("intCountryId").text();
$("#select2-selCountry-container").text($(this).find("strCountryName").text());
$('#selCountry').trigger('change');
selStateId = $(this).find("intStateId").text();
$('#selState').trigger('change');
$("#select2-selState-container").text($(this).find("strStateName").text());
selCityId = $(this).find("intCityId").text();
$('#selCity').trigger('change');
$("#select2-selCity-container").text($(this).find("strCityName").text());
}
=======================================================================
function getCountry() {
$.ajax({
type: "POST",
url: "Country.aspx/GetCountry",
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "JSON",
success: function (response) {
var name = "#selCountry";
var ddl = $(name);
var Col_Key = "intCountryID";
var Col_val = "strCountryName";
ddl.find('option').remove();
$(response.d).find("tblCountry").each(function () {
var OptionValue = $(this).find(Col_Key).text();
var OptionText = $(this).find(Col_val).text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
ddl.append(option);
});
$(ddl).val('0');
},
failure: function (response) {
}
});
});
}
=======================================================================
function getState() {
$.ajax({
type: "POST",
url: "State.aspx/GetState",
data: JSON.stringify({
COUNTRYID: countryid,
ACTION: Action
}),
contentType: "application/json; charset=utf-8",
dataType: "JSON",
success: function (response) {
var name = "#selState";
var ddl = $(name);
var Col_Key = "intStateID";
var Col_val = "strStateName";
ddl.find('option').remove();
$(response.d).find("tblState").each(function () {
var OptionValue = $(this).find(Col_Key).text();
var OptionText = $(this).find(Col_val).text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
ddl.append(option);
});
$(ddl).val('0');
},
failure: function (response) {
}
});
}
=======================================================================
function getCity() {
$.ajax({
type: "POST",
url: "City.aspx/GetCity",
data: JSON.stringify({
STATEID: countryid,
ACTION: Action
}),
contentType: "application/json; charset=utf-8",
dataType: "JSON",
success: function (response) {
var name = "#selCity";
var ddl = $(name);
var Col_Key = "intCityID";
var Col_val = "strCityName";
ddl.find('option').remove();
$(response.d).find("tblCity").each(function () {
var OptionValue = $(this).find(Col_Key).text();
var OptionText = $(this).find(Col_val).text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
ddl.append(option);
});
$(ddl).val('0');
},
failure: function (response) {
}
});
}
=======================================================================
function Edit()
{
var intddlCountry = '0', strddlCountry = '0', intddlState = '0', strddlState = '0', intddlCity = '0', strddlCity = '0';
$(response.d).find("tblInvoice").each(function () {
intddlCountry = $(this).find("intCountryId").text();
strddlCountry = $(this).find("strCountryName").text();
intddlState = $(this).find("intStateID").text();
strddlState = $(this).find("intState").text();
intddlCity = $(this).find("intCityID").text();
strddlCity = $(this).find("strCityName").text();
$.ajax({
url: getCountry(),
async: true,
success: function (response) {
$("#selCountry").val(intddlCountry);
$("#select2-selCountry-container").text(strddlCountry);
$.ajax({
url: GetState(),
async: true,
success: function (response) {
$("#selState").val(intddlState);
$("#select2-selState-container").text(strddlState);
$.ajax({
url: getCity(),
success: function (response) {
$("#selCity").val(intddlCity);
$("#select2-selCity-container").text(strddlCity);
}
});
}
});
}
});
});
}

How to know the page on which other user is

this is my code for a simple chatbox basically what does this does is on clicking send(input) button it will send the message into database and also create notification for the reciever but I want to create notification only when the user is not the this this page i.e on /message.php. Is there any way I can know on which the other user is? or any other approach to what I am trying to do?
$(".chatbox input").on("click", function () {
var rly = $("#reply").val();
var send = "<?php echo $Sender?>";
$.ajax({
type: 'POST',
url: 'Message_chat.php',
data: {
repl: rly
},
dataType: 'json',
success: function (data) {
document.getElementById("reply").value = "";
populatedata(data, send);
},
error: e => console.log(e)
});
});
function fetchdata() {
var send = "<?php echo $Sender?>";
$.ajax({
type: 'GET',
url: 'Message_chat.php',
dataType: 'json',
success: function (data) {
populatedata(data, send);
notification();
}
});
}
function notification() {
var notify = "";
$.ajax({
type: 'GET',
url: 'notify.php',
dataType: 'json',
success: function (data) {
if (data == null)
{
document.getElementsByClassName("ncircle")[0].style.display = "none";
} else {
var len = data.length;
for (var i = 0; i < len; i++) {
if (data[i].nread == 0) {
notify += "<p>" + data[i].nby + " sent you a message</p>";
}
}
$("#myDropdown").html(notify);
if (data.length != 0) {
document.getElementsByClassName("ncircle")[0].style.display = "block";
$(".ncircle").html(len);
}
}
},
error: e => console.log(e)
});
}

how to use json data sent from backend

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part
You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!
In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},
var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

Fill Variable with Web Service Results

I have a javascript function that is executed onClick via jquery. Within this function I am calling a Web Service "getTestConnection" which returns a True or False and I have confirmed it is working but keeps returning variable undefined.
$("#btnNext2").click(function() {
var postData = {}; {
postData['user'] = user;
postData['password'] = password;
postData['serviceurl'] = serviceurl;
postData['datasource'] = datasource;
};
//Converts object to string and formats to JSON
var json = JSON.stringify(postData);
//connTest keeps getting returned as 'Undefined'
var connTest = getTestConnection(json);
});
< script type = "text/javascript" >
function getDocType(json, rowcount) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/GetDocTypes",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//*****************************************************************************
//This is being called immediately after getTestConnection is executed
//******************************************************************************
for (i = 0; i < data.d.length; i++) {
$('#SelectDocType' + rowcount + '')
.append($("<option></option>")
.attr("value", data.d[i].docTypeID)
.text(data.d[i].docTypeName));
}
var firstDocTypeID = data.d[0].docTypeID;
var jsonUnstringify = JSON.parse(json);
var postDataNew = {}; {
postDataNew['user'] = jsonUnstringify.user;
postDataNew['password'] = jsonUnstringify.password;
postDataNew['serviceurl'] = jsonUnstringify.serviceurl;
postDataNew['datasource'] = jsonUnstringify.datasource;
postDataNew['docTypeID'] = firstDocTypeID;
};
var jsonnew = JSON.stringify(postDataNew);
getKeywords(jsonnew, rowcount);
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
//Test Connection Web Service
function getTestConnection(json) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/TestConnection",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
}
< /script>
You have multiples errors:
You have a <script type = "text/javascript"> tag inside another <script> tag
You define a new function inside another function:
function getDocType(json, rowcount) {
$.ajax({
.....
});
function getTestConnection(json) {
....
}
}
which should be
function getDocType(json, rowcount) {
$.ajax({
.....
});
}
function getTestConnection(json) {
....
}
You forgot to get returned data from the AJAX call in your getTestConnection function :
$.ajax({
type: "POST",
url: "http://localhost...",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
....
}
});

Categories

Resources