Wikipedia API sandbox, search by user's input - javascript

Trying to search in Wikipedia by user's input but it doesn't work for some reason. First I thought it could be due to cross domain problem. But .ajax should help with that.
Here is codepen: http://codepen.io/ekilja01/pen/pRerpb
Here is my HTML:
<script src="https://use.fontawesome.com/43f8201759.js">
</script>
<body>
<h2 class="headertext">WIKIPEDIA <br> VIEWER </h2>
<div class="row">
<div class="col-10-md">
<input class="searchRequest blink_me" id="cursor" type="text" placeholder="__"></input>
</div>
<div class="searchIcon col-2-md"> </div>
</div>
<div>
<p class=results></p>
</div>
</body>
Here is my jQuery:
$(document).ready(function() {
var icon = "<i class='fa fa-search fa-2x'></i>";
$('#cursor').on("keydown", function() {
$(this).removeClass("blink_me");
var searchIcon = $(".searchIcon");
searchIcon.empty();
if ($(".searchRequest").val().length > 0) {
searchIcon.append(icon);
}
searchIcon.on("click", function() {
console.log("clicked!");
var search = $(".searchRequest").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + search + "&format=json&callback=?";
$.ajax({
dataType: "jsonp",
url: url,
success: function(data) {
$(".results").html(data[0]);
console.log(data[0]);
}
});
});
});
});
What am doing wrong? Please help.

There's an error in the order of load for your js.
The data object contains the text of the results in the array with index 2, which i assume is what you want to show, change it to
$(".results").html(data[2]);
You can check a modified version of your original code here
http://codepen.io/anon/pen/mRmGXG

Related

ASPNET MVC: I get "The view X or its master was not found or no view engine..." Error on Method that return JSON ContentResult

I have a method that return json ContentResult. I call on from JavaScript file like this:
$scope.GetUserRoles = function () {
$http({
method: "GET",
url: Current.VirtualUrl + "Store/Counting/GetUserRoles"
}).then(function mySucces(response) {
if (response.data.Status == 1) {
$scope.UserRoles = response.data.Data;
$scope.GetCountingList(0, false, "CountingId", "DESC");
}
else {
console.log(response);
$scope.ShowMessage(msgWarning, msgDataFromServerFail + response.data.Data);
}
}, function myError(response) {
});
}
When calling here GetUserRoles method doesn't fire and Response.Data get this error:
<link href="/MySite/Assets/css/pages/error.css" rel="stylesheet" />
<div class="page-500-full-page">
<div class="row">
<div class="col-md-12 page-500">
<div class=" number">
500
</div>
<div>
<h3>Oops! Something went wrong.</h3>
<p>
The view 'GetUserRoles' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Areas/iStore/Views/Counting/GetUserRoles.aspx
~/Areas/iStore/Views/Counting/GetUserRoles.ascx
~/Areas/iStore/Views/Shared/GetUserRoles.aspx
~/Areas/iStore/Views/Shared/GetUserRoles.ascx
~/Views/Counting/GetUserRoles.aspx
~/Views/Counting/GetUserRoles.ascx
~/Views/Shared/GetUserRoles.aspx
~/Views/Shared/GetUserRoles.ascx
~/Areas/iStore/Views/Counting/GetUserRoles.cshtml
~/Areas/iStore/Views/Counting/GetUserRoles.vbhtml
~/Areas/iStore/Views/Shared/GetUserRoles.cshtml
~/Areas/iStore/Views/Shared/GetUserRoles.vbhtml
~/Views/Counting/GetUserRoles.cshtml
~/Views/Counting/GetUserRoles.vbhtml
~/Views/Shared/GetUserRoles.cshtml
~/Views/Shared/GetUserRoles.vbhtml </p>
</div>
</div>
</div>
</div>
Any help will be much appreciated.
Thanks in advance.
try replacing:
url: Current.VirtualUrl + "Store/Counting/GetUserRoles"
with this:
url:"/Store/Counting/GetUserRoles"
or make sure, you have:
url:"/ControllerName/MethodName"
in url
I found the problem. Base controller class override OnActionExecuting method. And an if condition prevent coming here.
Thanks for your all advices.

change an element's text with variable id

I am designing a social network that has timeline and there is like button. I use AJAX to apply the like button on the server side. the problem is that I want to change the number of like for each post immediately after they have liked successfully. Because my elements are generated by for-each, I want to change the number of like for the exact element, I really have a problem with it.I am using thymeleaf.
I am looking for an idea that how to do this.
here is my html code:
<div class="col-sm-4">
<div class="row" >
<div class="col-sm-12">
<img th:if="${tweet.isFavorited()}" src="../static/images/like.png" th:src="#{/images/like.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
<img th:if="${!tweet.isFavorited()}" src="../static/images/dislike.png" th:src="#{/images/dislike.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
</div>
</div>
<div class="row">
<div class="col-sm-12" >
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
<h6 th:if="${!tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getFavoriteCount()}"></h6>
</div>
</div>
and it is my script code:
$(function () {
$(".like-img").click(function () {
event.preventDefault();
var $post = $(this);
var toSend = {
"tweetId": this.getAttribute("id")
}
$.ajax({
type : "POST",
contentType: "application/json; charset=utf-8",
url : "like",
data : JSON.stringify(toSend),
dataType : 'json'
}).done(function (data) {
if(data.status == "success") {
if ($($post).attr("src") == "/images/dislike.png") {
$($post).attr('src','/images/like.png');
}
else {
$($post).attr('src','/images/dislike.png');
}
return false;
}
});
});
})
Okay so to make this work you will need to assign unique ids to the like-count elements, something like so:
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}_like_count" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
Then you can retrieve the current count, increment it, and set the text of the count element. Something like so:
var currentCount = parseInt($('#'+toSend.tweetId+'_like_count').innerHtml)
var newCount = currentCount++;
$('#'+toSend.tweetId+'_like_count').text(newCount);

get multi data atrributes from element classes of response html

how to get muttiple data attribute from element classes of response html.
I can extract only data.
this is response.html
<div class="book" data-name="frozen" data-author="micheal" data-price="30">
Frozen
</div>
<div class="book" data-name="unbroken" data-author="jimmy" data-price="25">
Unbroken
</div>
<div class="book" data-name="carry on" data-author="alex" data-price="32">
Carry On
</div>
Ajax code here
function getData($scope){
$.ajax({
url: "/response.html",
dataType: "html",
success: function(response) {
var $response = $(response);
// not working
// var $book-data = $response.find('div.book').data({'name','author','price'});
var $bookData = $response.find('div.book').data('name');
alert($bookData);
}
});
}
I wish to get book-data as json or array to display in angular.
try this:
var bookData=Array();
$.get("stackTest.html", function(response) {
$.each($(response).find(".book"),function(ind,ele){
bookData.push($(ele).data());
});
console.log(bookData);
});
then you get an array with the data-object of each ".book" node
mike
Pretty easy:
var allData = [];
$('.book').each(function(i){
allData.push( $(this).data() );
});
console.log( allData );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="book" data-name="frozen" data-author="micheal" data-price="30">
Frozen
</div>
<div class="book" data-name="unbroken" data-author="jimmy" data-price="25">
Unbroken
</div>
<div class="book" data-name="carry on" data-author="alex" data-price="32">
Carry On
</div>

jqMobi dynamically update element with ajax data

Using jqmobi 1.2
I'm trying to update the content of a panel with the result of an ajax call.
Following panel will collect the string to search for.
<div id="register_form" class="panel" data-defer="" data-header="default" data-footer="register_footer" data-load="" data-unload="">
<form id="register_data" class="selected">
<fieldset class="scrollable" data-pull-scroller="true">
<legend class="toggelable" >Organization:</legend>
<div id=""class="toggelable">
<label for="seleced_org" >Bezeichnung:</label><br>
<input type="text" id="seleced_org" class="toggelable jq-ui-forms" ><br>
<a class="button icon magnifier" href="javascript:searchOrg();">Search</a>
</div>
</fieldset>
</form>
</div>
The button will call following function, where the success method will add elements to the panel with the id "org_options".
Ajax function:
var FOUNDORGS = [];
function searchOrg() {
var request = $('input[id=seleced_org]').val();
$.ajax({
url: mcTime.ASURL + "/OrgCheck",
dataType: "JSONP",
crossDomain: true,
data: {
maxRows: 12,
name_startsWith: request,
callback: ''
},
success: function(data) {
/*
* server response: [{"organisationId":1,"workerquantity":0,"name":"My_Org","street":"Org_Street 1","zipcode":"45454","city":"Org_City"}]
*/
FOUNDORGS = $.parseJSON(data);
if ($('fieldset[name="options"]').find('.matchingOrgs').length == 0) {
$('fieldset[name="options"]').append('<ul class="mc matchingOrgs"></ul>');
}
var toAppend = $('fieldset[name="options"]').find('.matchingOrgs')[0];
$(toAppend).html('');
for (var i = 0; i < FOUNDORGS.length; i++) {
var obj = FOUNDORGS[i];
var li = $('<li>\n\
<a class="orglink" href="javascript:showOrgDetail(\'' + obj.organisationId + '\',\'' + obj.name + '\');">' + obj.name + '</a>\n\
</li>');
$(toAppend).append(li);
}
$.ui.loadContent('#org_options', false, false, 'slide');
}
});
}
appended div:
<div id="org_options" class="panel" data-header="default" data-footer="register_footer" modal="false" data-unload="">
<fieldset name="options" class="mc scrollable" data-pull-scroller="true">
<legend >Results:</legend>
</fieldset>
</div>
All this works fin in my browser (chrome), and with the XDK emulator but not on my iPhone when using the XDK app-tester.
Any body any idea??
I'm the lead dev on App Framework. There's a bug in the iOS container with handling JSON data from remote servers. There are some posts over at http://forums.html5m.com about it. It's logged internally in our bug tracking system.
thanks,
Ian

Why isn't my viewModel working

I'm struggling with this 3 days and can't get my mind around why the first viewModel is working but second isn't , it even doesn't allow me console.log() anything.
My view Models and ko bindings:
// KO View Models
var indexViewModel = {
item: ko.observableArray([]),
cat: ko.observableArray([]),
loadcontent: function () {
alert("inside index function");
$.ajax({
url: '/api/item/all',
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
indexViewModel.item(getArray);
}
});
$.ajax({
url: '/api/category/all',
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
indexViewModel.cat(getArray);
}
});
}
};
var dataReal = null;
var itemViewModel = {
item: ko.observableArray([]),
loadcontent: function (getID) {
alert(getID);
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
itemViewModel.item(getArray);
dataReal = data;
},
error: function (xhr, status) {
switch (status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error ' + status);
}
}
});
}
};
var mainViewModel = {
indexPage: indexViewModel,
itemPage: itemViewModel
};
ko.applyBindings(mainViewModel);
My working HTML:
<div id="index-content" data-bind="init: mainViewModel.indexPage.loadcontent(), with: mainViewModel.indexPage">
<div class="item-list" data-bind="foreach: item">
<div class="item-container clearfix">
<div class="item-content clearfix">
<div class="title" data-bind="text: Title">
</div>
<div class="left-side clearfix">
<div class="item-image" data-bind="style: { backgroundImage: 'url(content/u/'+Image+')' }">
</div>
<div class="item-descr">
<div class="body" data-bind="text: Body">
</div>
<div class="item-more-details">
Vairāk...
</div>
</div>
</div>
And the HTML witch even ignores my console.log() calls:
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
int id = ViewBag.id;
}
<div id="item-details-content">
<input type="hidden" id="item-id" value="#id" data-bind=""/>
<div class="item-list" data-bind="init: itemPage.loadcontent(#id), with: itemPage.item">
<div class="item-container clearfix" data-bind="init: console.log($root)">
<div class="item-content clearfix">
<div class="title" data-bind="text: Title">
</div>
<div class="left-side clearfix">
<div class="item-image" data-bind="style: { backgroundImage: 'url(content/u/'+Image+')' }">
</div>
<div class="item-descr">
<div class="body" data-bind="text: Body">
</div>
<div class="item-more-details">
Vairāk...
</div>
</div>
</div>
Questions
What am I doing wrong?
Where is syntax errors?
How can I get console.log() working there?
Maybe there is an alternative to my problem, maybe I'm misunderstanding the concept of KO.js?
Conclusions
I know there is data inside mainViewModel.itemPage.loadcontent($.ajax(data)) because alert() shows it, but it doesn't pass the value to item!
I'm a newbie, total newbie, and if I thought I'am somewhat a decent programmer now I think I am total dumb ass and I am starting to hate KO.js, but I need it very badly!
NOTE: You can see in debug section that index page works just fine.
DEBUG PLACE
Here is published web application
And here is single item page
THANK YOU
Thanks everyone for helping me, I was so frustrated that I even didn't see any more the obvious, thanks again! Cheers!
1) At first glance, I noticed your HTML bindings are referring to mainViewModel. For example:
data-bind="init: mainViewModel.itemPage.loadcontent(#id), with: mainViewModel.itemPage.item
should likely be
data-bind="init: itemPage.loadcontent(#id), with: itemPage.item
You are already bound to mainViewModel
2) For debugging, use this to see what you are bound to in the view.
<pre data-bind="text:ko.toJSON(yourViewModelGoesHere, null, 2)"></pre>
3) The data being returned is not an array, though you are treating it as such.
$.ajax({
url: '/api/item/details/' + getID,
dataType: 'json',
success: function (data) {
var getArray = [];
$.each(data, function (index, item) {
getArray[index] = item;
});
itemViewModel.item(getArray);
dataReal = data;
},
If you create a sample at http://jsfiddle.net we can help you more.
Within the data-bind elements, you are referring to your model relative the the object you specified in the applyBindings() function. In your case, you called applyBindings(mainViewModel), so in the bindings themselves, you refer to its properties, not to mainViewModel itself.
In your non-working HTML, <div class="item-container clearfix" data-bind="console.log($root)"> seems suspicious. What kind of binding is this? It doesn't specify any particular property to bind.
Use your browser's developer tools (Firebug in Firefox, Developer Tools in Chrome/IE...) to see the syntax errors. If there are problems with bindings, you will see them there.

Categories