I'm trying to get my facebook posts using the facebook graph api.But due to variation of likes,comment,share key in json data I had to make a function that could handle the cases.But when I'm trying to call the function in the html code below it shows function undefined errror.Can anyone please help me!!
function getPostsFacebookInfo(){
$.ajax('https://graph.facebook.com/me/posts?access_token='+myFacebookToken,{
success : function(response){
$.each(response.data,function(index,response){
console.log(response);
var react=function (){
if(response.hasOwnProperty('likes'))
{
$('#reactions').append(`<li class="list-group-item">Likes:${response.likes.data.length}</li>`);
}
else
{
$(' #reactions').append(`<li class="list-group-item">Likes:0</li>`);
}
if(response.hasOwnProperty('comments'))
{
$('#reactions').append(`<li class="list-group-item">Comments:${response.comments.data.length}</li>`);
}else
{
$('#reactions').append(`<li class="list-group-item">Comments:0</li>`);
}
if(response.hasOwnProperty('shares'))
{
$('#reactions').append(`<li class="list-group-item">Shares:${response.shares.data.length}</li>`);
}else
{
$('#reactions').append(`<li class="list-group-item">Shares:0</li>`);
}
};
$('#panelbody').append(`
<div class="well">
<div class="row">
<div class="col-md-9">
<p>${response.message}</p>
<img src="${response.picture}" class="img-thumbnail">
</div>
<div class="col-md-3" id="reactions">
<script>react();</script>//function call here..
</div>
</div>
</div>`);
//end argument list
});
}
});// end ajax call
}// end get facebook info
getBasicFacebookInfo();
getPostsFacebookInfo();
Related
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.
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);
Im trying to build a learning app where at the moment it needs to get the first 7 posts from a subreddit and then if that is not already in the database add it to the database. However it runs both the if and else 7 times each for some reason and I cannot figure out why. Here is the helper method:
Template.posts.helpers({
posts : function () {
Meteor.call('getPosts', "tifu", function(e, results){
var result = JSON.parse(results.content).data.children;
Session.set('postsResults', result);
});
for(var i=0; i<7; i++){
var result = Session.get('postsResults')[i].data;
if(Posts.find({r_id: result.id}).count() == 0){
console.log("if");
} else {
console.log("else");
};
};
return Posts.find();
}
});
and the html side:
<template name="posts">
<div class="col-md-12 posts-div">
{{#each posts }}
<div class="col-md-8">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">{{ title }}</h3>
</div>
<div class="panel-body">{{{ body }}}</div>
<div class="panel-footer">
<div class="col-md-2">{{ score }}</div>
<div class="col-md-2 col-md-offset-3">{{ subreddit }}</div>
<div class="col-md-2 col-md-offset-3">{{ createdBy }}</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-primary">
</div>
</div>
{{/each}}
</div>
<hr>
</template>
I have replaced the insert code with simple console logs and these are the results I get:
if
if
if
if
if
if
if
else
else
else
else
else
else
else
When I run the Posts.find({r_id: result.id}).count() == 0 in the console I get false same with Posts.findOne({r_id: result.id}) == null but for some reason in javascript file it still runs the true portion and I then end up with like 50 copies of the same post which is what I am trying to avoid.
It is not optimal to use Meteor.call in a helper. The helper's function will re-run every time there is a reactive change. This is why it runs so many times.
Use the Template.onCreated callback instead:
Template.posts.onCreated(function() {
Meteor.call('getPosts', "tifu", function(e, results){
var result = JSON.parse(results.content).data.children;
Session.set('postsResults', result);
});
});
And your helper:
Template.posts.helpers({
posts : function () {
var r = Session.get('postsResults')
for(var i=0; i<7; i++){
if(!r) continue;
var result = r[i].data;
if(Posts.find({r_id: result.id}).count() == 0){
console.log("if");
} else {
console.log("else");
};
};
return Posts.find();
}
});
Second thing to keep in mind is Session.get('postsResults') will be null while the result of Meteor.call is returned, for a few hundred milliseconds. If you do Session.get('postsResults')[i].data you will get an exception.
This is why i added a conditional check to continue the loop if r is null. This way you wait for the result and the posts function will re-run and recalculate the results with the new data.
Im running into a really weird error in 3.4 Phonegap/Cordova.
I have tested the service call through fiddler on the web as well as used WEINRE.
Over the browser it runs without any errors, when compiled to run on build.phonegap.com it hangs up on the first service.
The html
<!-- Page 1 -->
<div data-role="page" id="keyword" class="page">
<div class="bg"></div>
<div class="page-wrapper">
<div class="logo"><img src="images/logo.png" alt="" width="325" height="105"/></div>
<div class="text1">Enter Code</div>
<div class="input">
<input type="text" name="keyword" placeholder="code" id="keyword-value" />
</div>
<div class="button" id="keyword-submit" >Submit</div>
<div class="text2">
If you do not have a<br>
code, click continue
</div>
<div class="button" id="keyword-continue">Continue</div>
</div>
Im running into issues when running the keyword-submit function, it doesn't navigate through it though it does in the browser.
app.js
$("#keyword").live("pageinit",
function()
{
$("#keyword-continue").click(
function()
{
$.mobile.changePage("#zip-code");
});
$("#keyword-submit").click(
function()
{
alert("Entered Keyword Submit");
var keyword = $("#keyword-value").val();
if($.trim(keyword) == '')
{
navigator.notification.alert('Please Enter code');
return false;
}
service.getListByKeyword(keyword,
function(response)
{
$.mobile.showPageLoadingMsg("loading");
var check = JSON.parse(response).responsecollection.Response.rss.rs;
if(check.isvalid == 0)
{
if (check.msg!=null)
{
navigator.notification.alert(check.msg);
$.mobile.hidePageLoadingMsg();
}
}
else
{
window.localStorage.setItem("email",check.email);
alert("storing email");
service.resellerId = check.rsid;
localStorage.resellerId = service.resellerId;
alert("set reseller Id");
service.getResellerSetting(
function(response)
{
alert("entered merchant");
service.resellerEmail = JSON.parse(response).responsecollection.Response.rts.rt.mlid;
localStorage.resellerEmail = service.resellerEmail;
var telefloraStatus = JSON.parse(response).responsecollection.Response.rts.rt.UseTeleflora;
window.localStorage.setItem("floraStatus",floraStatus);
});
alert("Navigating to new page");
$.mobile.changePage("#keyword-list?keyword="+keyword);
//window.open("#keyword-list?keyword="+keyword,keywordPage);
}
});
alert();
$.mobile.hidePageLoadingMsg();
});
});
I have set up alerts to see where its navigating in the browser and getting caught in the mobile side.
Last set of code is the index.js
getListByKeyword: function (keyword, result) {
service.sendRequest("Reseller", "IsValid", function(args) {
args.rscode = keyword;
}, result);
alert("Inside the service call *END*");
}
I really cant seem to wrap my head around why it would work in the broswer and not on the android build.
//please follow these steps to check your phonegap project is ready to perform action or not.
//1)include cordova js or phonegap file reference
<script type="text/javascript" src="cordova.js"></script>
//2)check phonegap is ready or not
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('ready');
}
</script>
after that perform any action
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.