I want to get total number of posts done by admin , here is a ptv sports page id , i tried my page id even , it is returning Data:array[object] = length 25, i have displayed it but if posts are 400 then what should i do do manage uninformed posts and show all of them
function p_post() {
FB.api("/209652442394600?fields=posts{admin_creator}", function (response)
{
var t = response.posts.data.length; });
}
the answer by default is 25, manage it
function p_post() {
FB.api("/209652442394600/posts?fields=admin_creator,name&limit=250", function (response) {
var t = response.data.length;
document.getElementById('tposts').innerHTML = t;
});
}
it works
Related
I'm not sure I'm even attempting the right thing. Heres my issue.
I'm loading data to a screen if the user is authenticated. Its a summary screen. I can click a item and it will send me to a new "details" page (window.location) . I'm passing the ID in the URL and then doing a GET request to get the details to display. When I implement my rules on the firebase DB, (".read": "auth != null"), I get a "401 Unauthorized" error in the console.
So somehow I need to either pass the user to the details.js or set Persistence somehow. Anyone have any suggestions?
THIS IS THE CODE FROM THE MAIN.JS
auth.onAuthStateChanged(user => {
console.log(user);
if (user) {
database.on('value', function(data) {
myData = data.val()
keys = Object.keys(myData)
buildProperties();
})
// tempBuild()
} else {
$('.eachProperty').empty()
$('.eachProperty').append($(`<h1>You must be signed in to view properties</h1>`))
}
})
$('body').on('click', '.singleProp', function() {
id = $(this).attr('id')
window.location = "/details.html?id=" + id
})
THIS IS THE CODE FROM THE DETAILS.JS
var myLocation = location.search.slice(4)
$.get(`https://XXXXXX.firebaseio.com/property/${myLocation}/.json`).then(myProperty)
function myProperty(prop) {
$('.propAddress').text(prop.address)
$('.zip').text(prop.zip)
if(prop.pictures){
for (var i = 0; i < prop.pictures.length; i++) {
var myImg = prop.pictures[i]
$('.imgContainer').append($(`<div class="eachPicDiv"><img src="${myImg}" alt="0" class="detailPic">
<ion-icon class="rBtn" name="arrow-redo-outline"></ion-icon>
</div`))
}
} else {
$('.imgContainer').append($(`<h1>THERE WERE NO PICTURES</h1>`))
}
}
You are using jQuery to fetch your data from Firebase Database,
$.get is a jQuery method, and for that to succeed you need to have some sort of auth token.
Firebase already provides best in class access, read more about access here.
Learn by example here.
I have a problem, I used a get and post function to retrieve and save some url in my database, but now I d like to update a variable count, that should rapresent the votes that every video get, and after that I shoul be able to disable the button that a user click to vote. So I'm having some troubles to make the update function, or I should use another post? But if so I probably create another element inside my DB or not?
so here there is my video and for now I set the video's id invisible using css, to test it and try to find the video with that specific id and make the update
<p class="invisible" id="idVideo"> {{item._id}} </p>
<iframe class="partecipant" v-bind:src="item.video.url"> </iframe>
<p id="voti" > {{item.voti.count}} </p>
<input type="button" id="buttonVoti" v-on:click="addVoto">
so here, when the user click the button with id= buttonVoti the v-on click call addVoto function
methods: {
...
//ALL THE OTHERS METHODS
...
...
...
//AND THEN THE ADDVOTO FUNCTION
addVoto : function () {
var self = this;
//self.videos[1].voti.count++
//console.log(self.videos._id);
var i = document.getElementById("idVideo");
var idVid =i.innerHTML;
console.log(idVid);
so here I can change the variable count, using self....count++ but I have to store and then retrieve again the same video with the new count updated.
here there is my model so the logic to access to the count should be this one
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var videoSchema = new Schema({
video : {
id : String,
url : String,
idchallenge : String
},
voti : {
count : {}
}
});
module.exports = mongoose.model('Video', videoSchema);
yes so I have a method called load video, that is activated when the user click a button called loadVideo
loadVideo : function (){
var linkYoutube = this.text;
console.log(linkYoutube);
//POST
axios.post('/video',{
method: 'post',
video: {
id: '1',
url: linkYoutube
},
voti: {
count: 0
}
});
and this is my get function,
getVideo: function () {
var self = this;
// Make a request for a user with a given ID
axios.get('/video')
.then(function (response) {
self.videos = response.data;
console.log(self.videos);
When you do you GET request to your video route, in your route logic, you should be able to use Mongoose count. Here is what that route might look like:
var Router = require('express').Router();
var mongoose = require('mongoose');
var Video = mongoose.model('Video');
Router.get('/videos', function(req, res) {
var response = {};
Video.find({}, function(queryErr, videos) {
if (!queryErr) {
response.videos = videos;
Video.count({}, function(countErr, count) {
if (!countErr) {
response.count = count;
res.status(200).send(response);
} else {
res.status(500).send(countErr);
}
});
} else {
res.status(500).send(queryErr);
}
});
});
module.exports = Router;
Here is a question about Mongoose count on Stack Overflow.
I use a image gallery plugin called Unite Gallery plugin in an ASP.NET MVC project in order to display images stored in database. However, loading all of the images at the same time takes too long time (because each photo is in 1MB-4MB size and loading 500 photos at the same time on page load is not a good idea) and I think there must be a better approach i.e. asenkron loading or partial loading. Here is my Razor and Controller code. I have a look at many pages on the wweb and docs, but there is not an example in the documentation page. Do you have any idea?
<div id="gallery" style="display:none;">
#foreach (var item in Model)
{
if (item.FileData != null)
{
var base64 = Convert.ToBase64String(item.FileData);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
<img alt='Image'
src="#imgSrc"
data-image="#imgSrc"
data-description='Image'>
}
}
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
var gallery = jQuery("#gallery").unitegallery({
gallery_theme: "default" //theme skin
});
gallery.on("item_change", function (num, data) {
if((num%15) == 0)
{
$.ajax({
url: '#Url.Action("List", "PhotoContest")',
data: { isAll: isAllChecked, page: num }, //??? I pass the page parameter???
success: function(data){
//call is successfully completed and we got result in data
//??? NO IDEA ???
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
});
});
</script>
public ActionResult List(string query)
{
var model = db.Photo.Select(m => new PhotoViewModel
{
Id = m.Id,
Name = m.Name,
StatusId = m.StatusId,
SubmitDate = m.SubmitDate,
FileAttachments = m.FileAttachments,
SubmitNo = m.SubmitNo
})
.ToArray();
return View("List", model);
}
Update:
After trying to apply #Kris's perfect approach, I encountered the error shown below. There is not a fix or solution regarding to this specific problem on the web. Any idea?
The image after page load overloads div and gallery borders as shown below:
Load 30 images at a time
Load remaining in Itemchange event available in Unite gallery
Main Page
<div id="gallery" >
<input type="hidden" id="galleryPage" value="0"/>
#HTML.Action("GalleryImages") //first load 30 items as PageNo = 0
</div>
<script type="text/javascript">
var gallery;
jQuery(document).ready(function () {
gallery = jQuery("#gallery").unitegallery({
gallery_theme: "default" //theme skin
});
gallery.on("item_change", function (num, data) {
//when item loaded equals to 15 or 30 or multiples of 15 another 30 items get loaded
if((num%15) == 0)
{
$.ajax({
url: '#HTML.Action("GalleryImages")'+"?pageNo="+jQuery("galleryPage").val(),
data: { isAll: isAllChecked },
success: function(data){
jQuery("gallery").append(data);//partial view with new images
jQuery("galleryPage").val(gallery.getNumItems()/30); //page number total items/number of items per page
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
});
});
</script>
Partial View (_galleryImages.cshtml)
#foreach (var item in Model)
{
if (item.FileData != null)
{
var base64 = Convert.ToBase64String(item.FileData);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
<img alt='Image'
src="#imgSrc"
data-image="#imgSrc"
data-description='Image'>
}
}
Controller
//Main View
public ActionResult List()
{
return View();
}
//Partial View
public Action GalleryImages(int PageNo)
{
int PageSize = 30;
var model = db.Photo.Select(m => new PhotoViewModel
{
Id = m.Id,
Name = m.Name,
StatusId = m.StatusId,
SubmitDate = m.SubmitDate,
FileAttachments = m.FileAttachments,
SubmitNo = m.SubmitNo
}).Skip(PageNo*PageSize).Take(PageSize).ToArray();
return PartialView("_galleryImages", model);
}
I don't think there's just one issue here. First, loading 100s of images all at once is going to be slow no matter what you do. For this point #Kris probably has the right idea. I'm unfamiliar with this particular library, but if it provides a way to progressively load in a handful of images at a time, you should definitely make use of that.
The second issue is that you're using base64-encoded data URIs. Images encoded in this way are roughly 150% as large as the actual image data itself. In other words, you're adding greater stress to an already stressed situation. Instead, you should have an action that returns the image data, something like:
public ActionResult GetImage(int id)
{
var image = db.Images.Find(id);
if (image == null)
{
return new HttpNotFoundResult();
}
return File(image.FileData, image.FileType);
}
You can get somewhat creative here by caching the database query result or even the entire response, but be advised that you'll need a significant amount of RAM, since you're going to be storing a lot of image data there.
Third, there's the issue of using a database to store image data in the first place. Just because databases provide a blob type, doesn't mean you need to use it. The most performant approach is always going to be serving directly from the filesystem, as IIS can serve static files directly, without involving all the ASP.NET machinery. Instead of storing the image data in your database, write the image to a filesystem location and then merely store the path to the image in the database. You could then optimize even further by actually offloading all the images to a CDN, ensuring super-fast delivery and taking virtually all load off your server.
<script type="text/javascript">
$(document).ready(function () {
function getPlanetFeeds() {
$("#planetFeedsDiv").load('/PlanetFeed/GetPlanetFeeds', function (data) {
});
var refreshPartial = setInterval(function () { getPlanetFeeds() }, 3000);
function myStopFunction() {
clearInterval(refreshPartial);
}
<div id="planetFeedsDiv">
</div>
I am trying to get Feed from database when updated in it but the problem is that if i am uploading the video than it is getting refresh and not able to watch video continuously
if i am removing this function of time interval or increasing the time interval
var refreshPartial = setInterval(function () { getPlanetFeeds() }, 3000);
function myStopFunction() {
clearInterval(refreshPartial);
}
than i am not able to get updated feed regularly
and i am getting the planetfeed from controller as follows
public ActionResult GetPlanetFeeds()
{
var planetfeedsOrder = from a in db.PlanetFeeds
join c in db.Graphs
on a.PlanetFeedItemGraphId equals c.GraphID
join u in db.UserInfos
on c.ItemUserID equals u.UserID
orderby a.PostDate descending
select new UserInfoViewModel
{
FirstName = u.FirstName,
LastName = u.LastName,
UserID = u.UserID,
AvatarURL = u.AvatarURL,
GraphItemDescription = c.GraphItemDescription,
GraphItemURL = c.GraphItemURL,
GraphID = c.GraphID,
ItemType = c.ItemType,
ItemUserID = c.ItemUserID,
GraphItemTitle = c.GraphItemTitle
} ;
return PartialView("_PlanetFeeds", planetfeedsOrder.ToList());
}
check count with old and update value by searching in database and call getPartial method when NewDataCount is greater than old data
I was using search api to fetch tweets of a particular user. It worked perfectly except that it couldn't fetch tweets where username contained numbers.
So upon suggestion I replaced the query with that of status api. But am unable to parse it now!!
Posting below the old code to display the tweet details.
function displayTweets(data) {
//var data = JSON.parse(d);
$("#heading").html("Tweets: <span class='handleName'>#"+handle+"</span>");
$("#loading").remove();
$("#tweets").children().remove();
alert("1");
$.each(data.results, function(i, tweet) {
alert("hi");
if(tweet.text !== undefined) {
// Calculate how many hours ago was the tweet posted
var date_tweet = new Date(tweet.created_at);
var date_now = new Date();
var date_diff = date_now - date_tweet;
var hours = Math.round(date_diff/(1000*60*60)); // calc time to tweet in hours
if(hours < 1){
hours = Math.round(date_diff/(1000*60));
if(hours<1){
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--a moment ago.</span>"));
}else{
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--"+hours+" minute(s) ago.</span>"));
}
}else{
$("#tweets").append($("<li/>").html(tweet.text+" <span class='tweetTime'>--"+hours+" hour(s) ago.</span>"));
}
}
});
}
Now the query string i am using to get the response and store the response in localstorage:
function sendRequest(handle, noOfTweets, boolDisplay){
$.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+ handle + "&count=" + noOfTweets + "&callback=?", function(data) {
if(boolDisplay){
displayTweets(data);
}
localStorage.setItem("tweets"+handle, JSON.stringify(data));
});
Please tell me what changes are needed!!
}
The structures of the returned JSON is completely different. See the examples at https://dev.twitter.com/docs/api/1/get/search and https://dev.twitter.com/docs/api/1/get/statuses/user_timeline
For example, you're saying
$.each(data.results, function(i, tweet) {
But the user timeline doesn't contain a results element.
You want something like
$.each(data, (function(i, tweet) {