Cannot read property '_calendar' of undefined in moment.js - javascript

I am getting an error when someone is trying to submit an event on their calendar to be saved to the server. Any help is appreciated, thank you for your time! Please let me know if you guys are needing anymore specific information.
UPDATE: It seems that when I switched from pushing to an array myself when a event is added to the calendar via the drop feature from fullcalendar, then it works ok but I had issues with that code so I used clientevents from fullcalendar instead and now I am getting this error. Any ideas on what a fix might be for this?
I am getting the following error:
Uncaught TypeError: Cannot read property '_calendar' of undefined at D (moment.min.js:6) at e (jquery-1.11.3.min.js:5) at Vb
(jquery-1.11.3.min.js:5) at Vb (jquery-1.11.3.min.js:5) at Vb
(jquery-1.11.3.min.js:5) at Function.m.param
(jquery-1.11.3.min.js:5) at Function.ajax (jquery-1.11.3.min.js:5)
at Object. (calendar:514) at Function.each
(jquery-1.11.3.min.js:2) at Object.success (calendar:500)
companyCalendar.blade.php
var emailContainer = {};
emailContainer.email = email;
console.log("AJAX call here to submit dropped events as guest.");
$.ajax({
type: "POST",
url: '/partialAccountCheck',
data: emailContainer,
success: function (data) {
console.log('success, proceed with adding events to the company calendar');
$.each(newEvents, function (i, event) {
if (event.title !== 'undefined' && event.title !== null && event.title !== undefined) {
console.log(JSON.stringify(event));
event.start = moment(event.start).toDate();
event.end = moment(event.end).toDate();
event.start = formatDate(event.start) + ' ' + event.start.getHours() + ':' + event.start.getMinutes() + ':00';
event.end = formatDate(event.end) + ' ' + event.end.getHours() + ':' + event.end.getMinutes() + ':00';
console.log('event start is: ' + event.start);
console.log('event end is: ' + event.end);
event.identifier = <?php echo json_encode($companyIdentifier) ?>;
event.email = email;
event.services = event.title;
event.startAppointmentTime = event.start;
event.endAppointmentTime = event.end;
console.log("AJAX call here adding dropped appointments as guest.");
$.ajax({
type: "POST",
url: 'submitCalendarEvent',
data: event,
success: function (data) {
console.log('success');
},
complete: function (data) {
console.log(data);
}
});
} else {
console.log('exclude from submission');
}
});
},
complete: function (data) {
console.log(data);
}
});

I solved the problem creating variables for event.start and event.end.
start=moment(event.start).format('Y-MM-DD HH:mm:ss');
end=moment(event.end).format('Y-MM-DD HH:mm:ss');
$.ajax({
url:"insert.php",
type:"POST",
data:{title:event.title, start:start, end:end},

you need to convert your date from date format to string.
event.start = moment(event.start).format('YYYY-MM-DD HH:mm:00');
event.end = moment(event.end).format('YYYY-MM-DD HH:mm:00');

Related

My site does not open, stays on the white screen, raises "Object doesn't support property or method 'validator'" error

That's error ; When I followed the console screen while the page was loading it gave the error "SCRIPT438: SCRIPT438: Object doesn't support property or method 'validator'". It is showing the error in the contact.js file.
I could not solve the problem. Can you help me ?
My code in contact.js :
$(function () {
$('.contact-form').validator();
$('.contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "vendor/contact/contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">' + messageText + '</div>';
if (messageAlert && messageText) {
$('.contact-form').find('.messages').html(alertBox);
$('.contact-form')[0].reset();
}
}
});
return false;
}
})
});
There's no such method called 'validator'.
Assuming you're using the typical jquery validator plugin, what you're looking for is just 'validate()'

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

SyntaxError: missing ) after argument list Javascript

I am pretty new to Javascript. I tried to execute the function cs_sort_directory after the page has been loaded. I get the error Uncaught SyntaxError: missing ) after argument list.
window.onload = cs_sort_directory("http://sample.org/wp-admin/admin-ajax.php", "http://sample.org/wp-content/themes/directory-theme", "alphabetical", this);
What did I do wrong?
Here is the function cs_sort_directory:
function cs_sort_directory(admin_url,theme_url,sortType,obj){
var node_id = jQuery(obj).parents('.main-filter').data('node');
var form_id = jQuery(obj).parents('.main-filter').data('form');
jQuery(obj).parents('.main-filter').addClass('slide-loader');
jQuery(obj).parents('.cs-filter-menu').children('li').removeClass('active');
jQuery(obj).parents('li').addClass('active');
jQuery('#cs_sort_value').val(sortType);
jQuery(".ajax-loading").html('<i class="icon-spinner8 icon-spin"></i>').fadeIn();
var dataString = jQuery('#directory-filters-form').serialize() + "&sort=" + sortType+"&node_id=" + node_id;
jQuery.ajax({
type:"POST",
url: admin_url,
data: dataString,
success:function(response){
if(response.match('session_destroyed') ) {
jQuery(".ajax-loading").html('');
jQuery(obj).parents('.main-filter').append(response);
} else {
jQuery(obj).parents('.dynamic-listing').children('.cs-listing-wrapper').html(response);
jQuery(".ajax-loading").html('');
jQuery(obj).parents('.main-filter').removeClass('slide-loader');
}
}
});
//return false;
}

SharePoint 2013 get current user using JavaScript

How to get current user name using JavaScript in Script Editor web part?
Here is the code that worked for me:
<script src="/SiteAssets/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script src="/SiteAssets/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
alert(loginName);
}
function onError(error) {
alert("error");
}
</script>
I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.
//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});
Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.
If you are in a SharePoint Page just use:
_spPageContextInfo.userId;
How about this:
$.getJSON(_spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser")
.done(function(data){
console.log(data.Title);
})
.fail(function() { console.log("Failed")});
You can use the SharePoint JSOM to get your current user's account information. This code (when added as the snippet in the Script Editor web part) will just pop up the user's display and account name in the browser - you'll want to add whatever else in gotAccount to get the name in the format you want.
<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
var personProperties;
SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.UserProfiles.js');
function getCurrentUser() {
var clientContext = new SP.ClientContext.get_current();
personProperties = new SP.UserProfiles.PeopleManager(clientContext).getMyProperties();
clientContext.load(personProperties);
clientContext.executeQueryAsync(gotAccount, requestFailed);
}
function gotAccount(sender, args) {
alert("Display Name: "+ personProperties.get_displayName() +
", Account Name: " + personProperties.get_accountName());
}
function requestFailed(sender, args) {
alert('Cannot get user account information: ' + args.get_message());
}
</script>
See the SP.UserProfiles.PersonProperties documentation in MSDN for more info.
To get current user info:
jQuery.ajax({
url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" }
}).done(function( data ){
console.log( data );
console.log( data.d.Title );
}).fail(function(){
console.log( failed );
});
U can use javascript to achive that like this:
function loadConstants() {
this.clientContext = new SP.ClientContext.get_current();
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
//U must set a timeout to recivie the exactly user u want:
function onQuerySucceeded(sender, args) {
window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {
console.log(args.get_message());
}
//By using a proper timeout, u can get current user :
function ttt(){
var clientContext = new SP.ClientContext.get_current();
var groupCollection = clientContext.get_web().get_siteGroups();
visitorsGroup = groupCollection.getByName('OLAP Portal Members');
t=this.currentUser .get_loginName().toLowerCase();
console.log ('this.currentUser .get_loginName() : '+ t);
}
I had to do it using XML, put the following in a Content Editor Web Part by adding a Content Editor Web Part, Edit the Web Part, then click the Edit Source button and paste in this:
<input type="button" onclick="GetUserInfo()" value="Show Domain, Username and Email"/>
<script type="text/javascript">
function GetUserInfo() {
$.ajax({
type: "GET",
url: "https://<ENTER YOUR DOMAIN HERE>/_api/web/currentuser",
dataType: "xml",
error: function (e) {
alert("An error occurred while processing XML file" + e.toString());
console.log("XML reading Failed: ", e);
},
success: function (response) {
var content = $(response).find("content");
var spsEmail = content.find("d\\:Email").text();
var rawLoginName = content.find("d\\:LoginName").text();
var spsDomainUser = rawLoginName.slice(rawLoginName.indexOf('|') + 1);
var indexOfSlash = spsDomainUser.indexOf('\\') + 1;
var spsDomain = spsDomainUser.slice(0, indexOfSlash - 1);
var spsUser = spsDomainUser.slice(indexOfSlash);
alert("Domain: " + spsDomain + " User: " + spsUser + " Email: " + spsEmail);
}
});
}
</script>
Check the following link to see if your data is XML or JSON:
https://<Your_Sharepoint_Domain>/_api/web/currentuser
In the accepted answer Kate uses this method:
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")
you can use below function if you know the id of the user:
function getUser(id){
var returnValue;
jQuery.ajax({
url: "http://YourSite/_api/Web/GetUserById(" + id + ")",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function(data) {
var dataResults = data.d;
alert(dataResults.Title);
}
});
}
or you can try
var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
try this code..
function GetCurrentUsers() {
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
var currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
function onQuerySucceeded() {
var currentUsers = currentUser.get_title();
document.getElementById("txtIssued").innerHTML = currentUsers;
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
}
You can use sp page context info:
_spPageContextOnfo.userLoginName

How to Create Relationship Between Contact and Account SugarCRM javascript

Hi can somebody help me? I am new in programing with Javascript and I need to set a Contact to Account Relationship.
function SetRelationContact_Account(){
$.get(CurrentServerAddress + '/service/v2/rest.php', {
method: "set_relationship",
input_type: "JSON",
response_type: "JSON",
rest_data: '{"session":"' + SugarSessionId +
'","module_name":"Contacts","module_id":"' + CurrentContactId +
'","link_field_name":"accounts","related_ids":["session":"' + SugarSessionId +
'"]}'
}, function(data) {
if (data !== undefined) {
var addAccountResult = jQuery.parseJSON(data);
}
});
}
I tried to create new Contact and I want to set a Relationship with an existing Account.
At jmertic's suggestion, I tried the following, but it still didn't work:
function SetRelationContact_Account(){
$.get(CurrentServerAddress + '/service/v2/rest.php', {
method: "set_relationship",
input_type: "JSON",
response_type: "JSON",
rest_data: '{"session":"' + SugarSessionId + '","module_name":"Contacts","module_id":"' + CurrentContactId + '","link_field_name":"accounts","related_ids":["name":"account_id","value":"' + CurrentAccountId + '"]}'
}, function(data) {
if (data !== undefined) {
var addAccountResult = jQuery.parseJSON(data);
}
});
}
"related_ids" should be the Account Id of the record you are relating to, and should be in the form of a javascript array.

Categories

Resources