Profile image not loading from delve on Sharepoint - javascript

I'm trying to get the profile image from delve and display it on a Sharepoint page using Javascript,the problem i'm getting is that the image isn't loading always
var profileimage="https://eur.delve.office.com/mt/v3/people/profileimage?userId="+userInfo["SPS-ClaimID"]+"&size=L";

If you want to display the profile image, we can use the url as below.
var profileimage="/_layouts/15/userphoto.aspx?size=L&username=lz#tenant.onmicrosoft.com";
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id,Title,Email";
$.ajax({
url: url,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items=data.d.results;
var options="<option>--select a user--</option>";
for(var i=0;i<items.length;i++){
if(items[i].Email!=""){
options+="<option value='"+items[i].Email+"'>"+items[i].Title+"</option>";
}
}
$("#SiteUsers").html(options);
},
error: function (data) {
}
});
$("#SiteUsers").change(function(){
var html="";
if($(this).val()!=null&&$(this).val()!=""){
html+="<img src='/_layouts/15/userphoto.aspx?size=L&username=" + $(this).val() + "'/>";
}
if($(this).children(':selected').text()!=""){
html+="<p><span>Name:"+ $(this).children(':selected').text()+"</span></p>";
}
$("#UserInfomation").html(html);
});
});
</script>
<select id="SiteUsers"><option>--select a user--</option></select>
<div id="UserInfomation"></div>

Related

File upload progress Custom page RestAPI SPO

The code below is working fine to upload files to SPO through RestAPI. No feedback is received on file upload progress. An alert is thrown once the upload is complete.
I would like to have a progress bar to display the upload percentage and reload this upload page while clicking OK to the successful alert message.
Kindly assist.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function () {
init();
});
function init(){
$("#btnUploadFiles").click(function(){
var files=$("#inputTypeFiles")[0].files;
uploadFiles(files[0]); // uploading singe file
});
}
function uploadFiles (uploadFileObj) {
var fileName = uploadFileObj.name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary="TEST";
var folderName = "";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&#target='" + targetUrl + "'";
uploadFileToFolder(uploadFileObj, url, function (data) {
var file = data.d;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
departname: $("#departname").val(), //meta data column1
Filename: $("#filename").val(), //meta data column2
ACFTREG: $("#ACFTREG").val(), //meta data column3
Date: $("#datepicker").val() //meta data column4
};
url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";
updateFileMetadata(url, updateObject, file, function (data) {
alert("File uploaded & metadata updation done successfully");
}, function (data) {
alert("File upload done but metadata updating FAILED");
});
}, function (data) {
alert("File uploading and metadata updating FAILED");
});
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
var getFile = getFileBuffer(fileObj);
getFile.done(function (arrayBuffer) {
$.ajax({
url: apiUrl,
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
});
}
function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
$.ajax({
url: apiUrl,
type: "POST",
async: false,
data: JSON.stringify(updateObject),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Type": "application/json;odata=verbose",
"X-Http-Method": "MERGE",
"IF-MATCH": file.ListItemAllFields.__metadata.etag,
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
function getItems() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('L%20-%20MDB%20-%20ACFTREG')/items?$Select=Title&$top=2000",
type: "GET",
headers: {
"accept": "application / json;odata = verbose",
},
success: function(data) {
var results = data.d.results;
var options = "";
for(var i = 0; i < results.length; i++){
options = options + "<option value='" + results[i].Title + "'>" + results[i].Title + "</option>";
}
$("#ACFTREG").append(options);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
$( function() {$( "#datepicker" ).datepicker(
{
changeMonth: true,
changeYear: true
}
);} );
</script>
Select File:<input type="File" id="inputTypeFiles" /><br />
Departname: <input id="departname" type="textbox"/><br />
Date: <input type="text" id="datepicker" autocomplete="off" name="hidden"><br />
Filename: <input id="filename" type="textbox"/><br />
ACFTREG: <select id="ACFTREG" class="select">
<option selected="selected">Select</option><br />
<input type="button" id="btnUploadFiles" value="Upload"/><br />
Inside the $.ajax({}) function, you can add the xhr setting inside the ajax.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
// Place upload progress bar visibility code here
}
}, false);
return xhr;
},
type: 'POST',
//add the rest of ajax settings
check this link for ajax documentation
jQuery/ajax
check this link for example on upload progress
jQuery-upload-progress/example

Set field Originator Signature to Current User

Good day, I have a SharePoint form the has a Originator Completed Dropdown with Yes or No as options. If the dropdown is yes, I would like to use JavaScript to set the OriginatorSignature (Text Field) to the loginName or current user. Can someone assist with this function?
<script src="/SiteAssets/jquery-3.2.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
GetUserLogin();
});
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
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 : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
var loginName = data.d.LoginName.split('|')[1];
$("input[title='Originator Signature']").val(loginName);
}
function QueryError(error) {
alert(error);
}
</script>
The following code for your reference.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if($("select[title='Originator Completed Dropdown']").val()=="Yes"){
GetUserLogin();
}
$("select[title='Originator Completed Dropdown']").change(function(){
if($(this).val()=="Yes"){
GetUserLogin();
}else{
$("input[title='Originator Signature']").val("");
}
});
});
function GetUserLogin(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + _spPageContextInfo.userId + ")",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
var loginName = data.d.LoginName;
if(loginName.indexOf("|")!=-1){
loginName = loginName.split('|')[1];
}
$("input[title='Originator Signature']").val(loginName);
},
error: function (data) {
//alert("Error");
}
});
}
</script>

How to print json console.log data in browser?

I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.
script.js
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});
index.php
<input id="movie" type="text" /><button>Search</button>
This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.
Retrieve the specific values using key and show it. The object have keys and values. Doing object.key will give the value
$(document).ready(function() {
var url = 'https://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
$("#title").text(json.title);
//$("#movTitle").prop('src'); // add image path here
$("#overview").text(json.overview) //overview is a key
},
error: function(e) {
console.log(e.message);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<!-- Search This: 346364 -->
<div id="title">
</div>
<div>
<img id="movTitle" src="" alt="">
</div>
<div id="overview">
</div>
To output your JSON data to the browser, you need to modify the HTML of the page.
First, add a few elements to your index.php like so:
index.php
<input id="movie" type="text" /><button>Search</button>
<h1>Movie info:</h1>
<p>Movie title: <span id="movie-title"></span> </p>
<p>Movie budget: <span id="movie-budget"></span> </p>
Then, in your success callback that you are defining in the jQuery ajax request, you can grab the span elements and replace their text by using jQuery's text function like so:
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
// grab the span elements by ID and replace their text with the json text
$("#movie-title").text(json.title);
$("#movie-budget").text(json.budget);
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});

JQuery creating button but not clickable

I have code that creates the body of a html-file.
I create it with JQuery.
The code is as followed:
SCRIPT JS
$(document).ready(function(){
homePage();
});
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = $("<h1></h1>").text(data.title);
var br = $("<br>");
var eventbtn = $('<input />', {
type : 'button',
id : 'eventbutton',
value : 'Events',
on : {
click: getevents(data.events)
}
});
html.append(br,eventbtn).appendTo($("body"));
},
error: function(error){
console.log("the page was not loaded", error);
},
});
}
function getevents(url){
console.log(url);
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script src="script.js"></script>
</head>
</body>
</html>
The function homePage is directly called when you open the index.html.
It does work, I see a header and a button, however the code is automatically triggers, it prints the url in the console. But when I click on it, it doesn't print it in the console.
How do I need to change my code in order to get a button that only prints the given url when I click on the button?
Try setting data-url attribute and then access it using $(this):
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = $("<h1></h1>").text(data.title);
var br = $("<br>");
var eventbtn = $('<input />', {
type : 'button',
id : 'eventbutton',
value : 'Events',
});
eventBtn.addClass('dynamic-btn');
eventbtn.data('url', data.events);
html.append(br,eventbtn).appendTo($("body"));
},
error: function(error){
console.log("the page was not loaded", error);
}
});
}
$(document).on('click', '.dynamic-btn',
function (e) {
console.log($(this).data('url'));
});
Add click function to the button after it has already been appended to the body:
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = $("<h1></h1>").text(data.title);
var br = $("<br>");
var eventbtn = $('<input />', {
type : 'button',
id : 'eventbutton',
value : 'Events',
on : {
click: getevents(data.events)
}
});
html.append(br,eventbtn).appendTo($("body"));
eventbtn.click(getevents(data.events));
},
error: function(error){
console.log("the page was not loaded", error);
}
});
}
$(document).ready(function(){
homePage();
});
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = "<h1>"+data.title+"</h1>";
html += "<br>";
html += '<input type="button" id="eventbutton" value="Events"/> ';
$("body").append(html);
$('input').click(function(){
getevents(data.events);
});
},
error: function(error){
console.log("the page was not loaded", error);
},
});
}
function getevents(url){
console.log(url);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Retrieve data from Weather.asmx goes in error path-Javascript

I want to retrieve some data from Weather.asmx and wrote below code to get some data. There was no error from Javascript as I have seen but when the program runs it always go to groupPropertiesErrorHandler function. Any idea?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
$.ajax({
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=10007",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: groupPropertiesSuccessHandler,
error: groupPropertiesErrorHandler
});
});
function groupPropertiesSuccessHandler(data) {
var jsonObject = JSON.parse(data.body);
var properties = 'Group Properties:\n';
alert(properties);
}
// Error Handler
function groupPropertiesErrorHandler(data, errorCode, errorMessage) {
alert("Could not get the group properties: " + errorMessage);
}
});
</script>

Categories