<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
Related
Good morning. I am new to the coding world, so my skills growing daily. I am trying to activate a SharePoint 2013 list workflow by using a button and Javascript. I know there are plenty of examples available, and to be honest, I'm a bit embarrassed about not being able to figure this out myself. All the codes that I have seen to date however have initiation variables in them, but my workflow doesn't. I'm at a loss for how to alter the examples to exclude having initiation variables. Please help. Example code I have looked at:
http://ranaictiu-technicalblog.blogspot.com/2013/06/sharepoint-2013-start-workflow-with.html
https://www.codeproject.com/Articles/607127/Using-SharePoint-2013-Workflow-Services-JS-API#example5
https://sharepoint.stackexchange.com/questions/236329/start-sharepoint-designer-workflow-2013-using-javascript
I used the following code from first link:
//dialog element to show during processing
var dlg = null;
//Subscription id - Workflow subscription id
//list item id for which to start workflow. If site workflow, then send null for itemId
function StartWorkflow(subscriptionId, itemId) {
showInProgressDialog();
var ctx = SP.ClientContext.get_current();
var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
ctx.load(subscription, 'PropertyDefinitions');
ctx.executeQueryAsync(
function (sender, args) {
var params= new Object();
//Find initiation data to be passed to workflow.
var formData = subscription.get_propertyDefinitions()["FormData"];
if (formData != null && formData != 'undefined' && formData != "") {
var assocParams = formData.split(";#");
for (var i = 0; i < assocParams.length; i++) {
params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
}
}
if (itemId) {
wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
}
else {
wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);
}
ctx.executeQueryAsync(
function (sender, args) {
closeInProgressDialog();
},
function (sender, args) {
closeInProgressDialog();
alert('Failed to run workflow');
}
);
},
function (sender, args) {
closeInProgressDialog();
alert('Failed to run workflow');
}
);
}
function closeInProgressDialog() {
if (dlg != null) {
dlg.close();
}
}
function showInProgressDialog() {
if (dlg == null) {
dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Waiting for workflow...", null, null);
}
}
And inserted the following HTML to create the button.
<button onclick="function StartWorkflow('8E645164-959C-4358-B22C-47FDA93F7906',5)">Click Me</button>
I am 100% confident that my subscriptionId and my itemId are correct.
Please help.
Thank you.
My test code for your reference,it's just slightly different from your code:
<input type="button" id="test" value="Click Me" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/_layouts/15/sp.workflowservices.js"></script>
<script>
$("#test").click(function(){
console.log(1)
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', init);
function init() {
$.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.js'), function () {
$.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'), function () {
StartWorkflow("SubscriptionId","itemid","siteurl");
});
});
}
//dialog element to show during processing
var dlg = null;
//Subscription id – Workflow subscription id
//list item id for which to start workflow. If site workflow, then send null for itemId
//SiteURL – site collection where the workflow exists
function StartWorkflow(subscriptionId, itemId, SiteURL) {
showInProgressDialog();
var ctx = new SP.ClientContext(SiteURL);
var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
ctx.load(subscription, 'PropertyDefinitions');
ctx.executeQueryAsync(
function (sender, args) {
var params = new Object();
//Find initiation data to be passed to workflow.
var formData = subscription.get_propertyDefinitions()["FormData"];
if (formData != null && formData != 'undefined' && formData != "") {
var assocParams = formData.split(";#");
for (var i = 0; i < assocParams.length; i++) {
params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
}
}
if (itemId) {
wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
}
else {
wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);
}
ctx.executeQueryAsync(
function (sender, args) {
closeInProgressDialog(SiteURL);
},
function (sender, args) {
closeInProgressDialog(SiteURL);
$('#msg')[0].innerHTML = "Woops – something went wrong, the document may have already been reviewed";
}
);
},
function (sender, args) {
closeInProgressDialog(SiteURL);
$('#msg')[0].innerHTML = "Woops – something went wrong, the document may have already been reviewed";
}
);
}
function closeInProgressDialog(SiteURL) {
if (dlg != null) {
dlg.close();
$('#msg')[0].innerHTML = "Thank you – you can now close the page";
}
}
function showInProgressDialog() {
if (dlg == null) {
dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait…", "Waiting for workflow…", null, null);
}
}
})
</script>
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 cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...
I have this script below which is used in a survey. The problem I have is, onbeforeunload() works when I don't call a function inside it. If I make any function call(save_survey() or fetch_demographics()) inside it, the browser or the tab closes without any prompt.
<script type="text/javascript">
$(document).ready(function() {
$('#select_message').hide();
startTime = new Date().getTime();
});
loc = 0;
block_size = {{ block_size }};
sid = {{ sid }};
survey = {{ survey|tojson }};
survey_choices = '';
startTime = 0;
demographics_content = {};
function save_survey(sf)
{
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
var surveydat = '';
if(sf==1)
{ //Success
surveydat = 'sid='+sid+'&dem='+JSON.stringify(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+JSON.stringify(survey_choices);
}
if(sf==0)
{ //Fail
surveydat = 'sid='+sid+'&dem='+json_encode(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+json_encode(survey_choices);
}
//Survey Save Call
$.ajax({
type: 'POST',
url: '/save_surveyresponse/'+sf,
data: surveydat,
beforeSend:function(){
// this is where we append a loading image
$('#survey_holder').html('<div class="loading"><img src="/static/img/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$('#survey_holder').html('Success');
alert("Dev Alert: All surveys are over! Saving data now...");
window.location.replace('http://localhost:5000/surveys/thankyou');
},
error:function(){
// failed request; give feedback to user
$('#survey_holder').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
function verify_captcha()
{
// alert($('#g-recaptcha-response').html());
}
function block_by_block()
{
var div_content ='<table border="0" cellspacing="10" class="table-condensed"><tr>';
var ii=0;
var block = survey[loc];
var temp_array = block.split("::");
if(loc>=1)
{
var radio_val = $('input[name=block_child'+(loc-1)+']:checked', '#listform').val();
//console.log(radio_val);
if(radio_val!=undefined)
survey_choices += radio_val +'\t';
else
{
alert("Please select one of the choices");
loc--;
return false;
}
}
for(ii=0;ii<block_size;ii++)
{
//Chop the strings and change the div content
div_content+="<td>" + temp_array[ii]+"</td>";
div_content+="<td>" + ' <label class="btn btn-default"><input type="radio" id = "block_child'+loc+'" name="block_child'+loc+'" value="'+temp_array[ii]+'"></label></td>';
div_content+="</tr><tr>";
}
div_content+='<tr><td><input type="button" class="btn" value="Next" onClick="survey_handle()"></td><td>';
div_content+='<input type="button" class="btn" value="Quit" onClick="quit_survey()"></td></tr>';
div_content+="</table></br>";
$("#survey_holder").html(div_content);
//return Success;
}
function updateProgress()
{
var progress = (loc/survey.length)*100;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#active-bar").html(Math.ceil(progress));
}
function survey_handle()
{
if(loc==0)
{
verify_captcha();
$("#message").hide();
//Save the participant data and start showing survey
fetch_demographics();
block_by_block();
updateProgress();
$('#select_message').show();
}
else if(loc<survey.length)
{
block_by_block();
updateProgress();
}
else if(loc == survey.length)
{
//Save your data and show final page
$('#select_message').hide();
survey_choices += $('input[name=block_child'+(loc-1)+']:checked', '#listform').val()+'\t';
//alert(survey_choices);
//Great way to call AJAX
save_survey(1);
}
loc++;
return false;
}
</script>
<script type="text/javascript">
window.onbeforeunload = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
//fetch_demographics();
save_survey(0);
return "You have spent "+Math.ceil(t)+ " minute/s on the survey!";
//!!delete last inserted element if not quit
}
</script>
I have checked whether those functions have any problem but they work fine when I call them from different part of the code. Later, I thought it might be because of unreachable function scope but its not the case. I have tried moving the onbeforeunload() at the end of script and the problem still persists. Wondering why this is happening, can anyone enlighten me?
I identified where the problem was. I am using json_encode instead of JSON.stringify and hence it is crashing(which I found and changed already in sf=1 case). That tip with debugger is invaluable. Also, its working fine even without async: false.
Thank you again #AdrianoRepetti!
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