how to get users from sharepoint user profile db using jquery - javascript

i just want to know: Is there any way to get a SharePoint user using JavaScript/jQuery from default sharepoint-2010 user profile DB?
My requirement is to form an array of all SharePoint site users (user name) and use this array in a java function (that run behind the page at client side ) as a data source for a SPServices function.
Please provide any feasible solution or any other approach for building the array for JavaScript.
thanks

There are two ways to do it:
Use client object model (OM) for ECMAScript:
Get all users and groups client object model sharepoint 2010
SharePoint 2010: Client Object Model for JavaScript (ECMAScript)
The first article explains how to retrieve information about SharePoint users using OM and the second one shows how to use OM from JavaScript - you have to combine appropriate pieces of code.
Call appropriate method from the UserGroup service (e.g. GetAllUserCollectionFromWeb or GetUserCollection) using jQuery:
Calling the SharePoint Web Services with jQuery
Consuming WCF / ASMX / REST service using jQuery
Calling WCF Service using jQuery in Sharepoint Applications

Using SPServices from codeplex:
<script type="text/javascript">
$(document).ready (function() {
$().SPServices({
operation: "GetListItems",
async: true,
listName: "User Information List",
CAMLViewFields: "<ViewFields>" +
"<FieldRef Name='Title' />" +
"</ViewFields>",
completefunc: AttachMembersAutoComplete
});
});
function AttachMembersAutoComplete(xmlResponse) {
var domElementArray = $( "[nodeName=z:row]", xmlResponse.responseXML );
var dataMap = domElementArray.map(function() {
return {
value: $(this).attr('ows_Title'),
};
});
var data = dataMap.get();
$("input#inputMembersAutoComplete").autocomplete({
source: data,
select: function(e, ui){
var tmpHTML = ui.item['value'];
$("#person_info").html(tmpHTML);
}
});
}
</script>

Related

Simple web GUI to capture user data

I need to develop a simple web page that accepts user information( name, age, birthdate, etc) and saves the data to a CSV or a text file to the server. I currently use Google sheets, but I need something that's more customizable and something that does some simple error checking. Are there any open source frameworks out there that I can use to put something together in a couple hours? I have a mechanical engineering background, and I'm not too familiar with web technologies. Any pointers will be greatly appreciated.
jQuery
JavaScript:
function saveUserData(url, data) {
var csv = [], // the array of values
del = "="; // the "delimiter" or "separator"
function handle(string) {
return encodeURI(string)
.replace(/,/g, "%2c");
}
for(var property in data)
csv.push(property + del + handle(data[property]));
// "name=John Doe,dob=Jan 1%2c 2000"
$.post(url, {data: csv.toString()})
.done(function(returned_data) {
// if you need this later
}, "json");
// "url" the the url to send the data to
// "data:" will likely be determined by the server you're using
// "json" will make "returned_data" a JSON object (if the server supports it)
}
Tesla88,
In your case, you need to write a server-side script. Below are 3 links that will show you how to
open, write, and close a file.
That's how far as I would elaborate on my answer, you need to show us that you actually did the work, and if you ran into issues, you can ask here again.
I hope the above helps.
-Anthony

Use .ASPX file as a Server-Side code to be called via AJAX by HTML/Javascript Client

There are tools that are used by several thousand employees at my job. They are currently stored on SharePoint 2010 (to be upgraded to 2016 very soon) in a document library. Essentially, we're using SP2010 as a web server so we didn't have to charge a huge expense to our business unit for our own web server.
These tools are all based in HTML and JavaScript. However, I'm trying to automate the collection of data points that the user is currently inputting manually. To do this, I found that the best way would be to query the LDAP which is always going to be Server-Side code since there is no way to query the LDAP via the browser. Below, you'll see the JavaScript that I have and the ASPX file that I have (minus the header that sharepoint automatically creates). I'm sending an AJAX call over to the ASPX file with some data in the URL that will be needed to get the remaining data from the LDAP. However, what I'm getting back seems to be literally ALL of the code that is being stored by the browser versus the ONE JSON variable that I want.
First the JavaScript:
var ldapUserName;
var employee = {};
var ADSystem = new ActiveXObject("ADSystemInfo");
ldapUserName = ADSystem.UserName;
$.ajax({
type: "GET",
url: "http://my.url.where/i/am/storing/getEmp.aspx?username=" + ldapUserName,
success: function(data) {
employee = data;
alert(employee);
},
error: function() {
alert("Connection Failed");
}
});
Next, the ASPX file (minus the SharePoint header that's automatically added)
<%
Option Explicit
Response.LCID = 1043
%>
<!--#include file="jsonObject.class.aspx" -->
<%
Dim username
username = Request.QueryString("username")
empDemo(username)
Public Function empDemo(username)
'Create the Array that will be passed
Set JSON = New JSONobject
'Employee specific information
Set objUser = GetObject("LDAP://" & username)
JSON.Add "empNum", objUser.sAMAccountName
JSON.Add "fName", objUser.givenName
JSON.Add "lName", objUser.sn
JSON.Add "fullName", objUser.displayName
JSON.Add "ext", objUser.telephoneNumber
JSON.Add "title", objUser.title
JSON.Write()
End Function
%>
Notice that I'm pulling in a file which helps the VBScript work with JSON variables. That file can be found here.
Again, what getting back seems to be quite literally all of the source code of the ASPX file. What I need is to only get back the JSON variable. Anyone have any suggestions?
Your server does not know what an "aspx" file is. It thinks it is a text file and so its just returning the text of your file.
I am not sure how you would fix this as I am not familiar with Sharepoint. As Sharepoint is a document management system, It appears sharepoint is doing what it was built for. Storing documents and then allowing people to download them. There appears to be no interpreter on the Sharepoint servers for "aspx" files.
This URL might provide help in enabling this if it is even possible: https://support.microsoft.com/en-us/help/828810/how-to-enable-an-asp.net-application-to-run-on-a-sharepoint-virtual-server

How to call json rest service in html through dojo

I am developing an maven web application using rest web services. I am trying to call the simple web service from the dojo. But I did not know getting started to call rest service through dojo. My web service code is:
#GET
#Path("/users")
#Produces("application/json")
public ArrayList dynamicFetch() {
ArrayList<User> ar = new ArrayList<User>();
User u1 = new User(1,"Test",30);
ar.add(u1);
u1 = new User(2,"test2",31);
ar.add(u1);
return ar;
}
Which executes and shows
[{"age":30,"name":"Test","id":1},{"age":31,"name":"test2","id":2}]
How can i call this json object in html through dojo since all my elements are dojo..?
Please Help any help will be apprciated more
Thanks
Prior to dojo v1.7, try this:
dojo.xhrGet({
url: "/users",
handleAs:"json",
load: function (data) {
// data is the array object it responds.
console.log(data);
}
});
See the Dojo Ajax reference guide for details.

Get Twitter Feed as JSON without authentication

I wrote a small JavaScript a couple of years ago that grabbed a users (mine) most recent tweet and then parsed it out for display including links, date etc.
It used this json call to retrieve the tweets and it no longer works.
http://twitter.com/statuses/user_timeline/radfan.json
It now returns the error:
{"errors":[{"message":"Sorry, that page does not exist","code":34}]}
I have looked at using the api version (code below) but this requires authentication which I would rather avoid having to do as it is just to display my latest tweet on my website which is public anyway on my profile page:
http://api.twitter.com/1/statuses/radfan.json
I haven't kept up with Twitter's API changes as I no longer really work with it, is there a way round this problem or is it no longer possible?
Previously the Search API was the only Twitter API that didn't require some form of OAuth. Now it does require auth.
Twitter's Search API is acquired from a third party acquisition - they rarely support it and are seemingly unenthused that it even exists. On top of that, there are many limitations to the payload, including but not limited to a severely reduced set of key:value pairs in the JSON or XML file you get back.
When I heard this, I was shocked. I spent a LONG time figuring out how to use the least amount of code to do a simple GET request (like displaying a timeline).
I decided to go the OAuth route to be able to ensure a relevant payload. You need a server-side language to do this. JavaScript is visible to end users, and thus it's a bad idea to include the necessary keys and secrets in a .js file.
I didn't want to use a big library so the answer for me was PHP and help from #Rivers' answer here. The answer below it by #lackovic10 describes how to include queries in your authentication.
I hope this helps others save time thinking about how to go about using Twitter's API with the new OAuth requirement.
You can access and scrape Twitter via advanced search without being logged in:
https://twitter.com/search-advanced
GET request
When performing a basic search request you get:
https://twitter.com/search?q=Babylon%205&src=typd
q (our query encoded)
src (assumed to be the source of the query, i.e. typed)
by default, Twitter returns top 25 results, but if you click on
all you can get the realtime tweets:
https://twitter.com/search?f=realtime&q=Babylon%205&src=typd
JSON contents
More Tweets are loaded on the page via AJAX:
https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd&include_available_features=1&include_entities=1&last_note_ts=85&max_position=TWEET-553069642609344512-553159310448918528-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Use max_position to request the next tweets
The following json array returns all you need to scrape the contents:
https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd
has_more_items (bool)
items_html (html)
max_position (key)
refresh_cursor (key)
DOM elements
Here comes a list of DOM elements you can use to extract
The authors twitter handle
div.original-tweet[data-tweet-id]
The name of the author
div.original-tweet[data-name]
The user ID of the author
div.original-tweet[data-user-id]
Timestamp of the post
span._timestamp[data-time]
Timestamp of the post in ms
span._timestamp[data-time-ms]
Text of Tweet
p.tweet-text
Number of Retweets
span.ProfileTweet-action–retweet > span.ProfileTweet-actionCount[data-tweet-stat-count]
Number of Favo
span.ProfileTweet-action–favorite > span.ProfileTweet-actionCount[data-tweet-stat-count]
Resources
https://code.recuweb.com/2015/scraping-tweets-directly-from-twitter-without-authentication/
If you're still looking for unauthenticated tweets in JSON, this should work:
https://github.com/cosmocatalano/tweet-2-json
As you can see in the documentation, using the REST API you'll need OAuth Tokens in order to do this. Luckily, we can use the Search (which doesn't use OAuth) and use the from:[USERNAME] operator
Example:
http://search.twitter.com/search.json?q=from:marcofolio
Will give you a JSON object with tweets from that user, where
object.results[0]
will give you the last tweet.
Here is a quick hack (really a hack, should be used with caution as its not future proof) which uses http://anyorigin.com to scrape twitter site for the latest tweets.
http://codepen.io/JonOlick/pen/XJaXBd
It works by using anyorigin (you have to pay to use it) to grab the HTML. It then parses the HTML using jquery to extract out the relevant tweets.
Tweets on the mobile site use a div with the class .tweet-text, so this is pretty painless.
The relevant code looks like this:
$.getJSON('http://anyorigin.com/get?url=mobile.twitter.com/JonOlick&callback=?', function(data){
// Remap ... utf8 encoding to ascii.
var bar = data.contents;
bar = bar.replace(/…/g, '...');
var el = $( '<div></div>' );
el.html(bar);
// Change all links to point back at twitter
$('.twitter-atreply', el).each(function(i){
$(this).attr('href', "https://twitter.com" + $(this).attr('href'))
});
// For all tweets
$('.tweet-text', el).each(function(i){
// We only care about the first 4 tweets
if(i < 4) {
var foo = $(this).html();
$('#test').html($('#test').html() + "<div class=ProfileTweet><div class=ProfileTweet-contents>" + foo + "</div></div><br>");
}
});
});
You can use a Twitter API wrapper, such as TweetJS.com which offers a limited set of the Twitter API's functionality, but does not require authentication. It's called like this;
TweetJs.ListTweetsOnUserTimeline("PetrucciMusic",
function (data) {
console.log(data);
});
You can use the twitter api v1 to take the tweets without using OAuth. For example: this link turns #jack's last 100 tweets.
The timeline documentation is here.
The method "GET statuses/user_timeline" need a user Authentification like you can see on the official documentation :
You can use the search method "GET search" wich not require authentification.
You have a code for starting here : http://jsfiddle.net/73L4c/6/
function searchTwitter(query) {
$.ajax({
url: 'http://search.twitter.com/search.json?' + jQuery.param(query),
dataType: 'jsonp',
success: function(data) {
var tweets = $('#tweets');
tweets.html('');
for (res in data['results']) {
tweets.append('<div>' + data['results'][res]['from_user'] + ' wrote: <p>' + data['results'][res]['text'] + '</p></div><br />');
}
}
});
}
$(document).ready(function() {
$('#submit').click(function() {
var params = {
q: $('#query').val(),
rpp: 5
};
// alert(jQuery.param(params));
searchTwitter(params);
});
})

Backbone.js without REST using ASP .net webservice

(sorry for the english)
I have a ASP .net webservice that get data from a oracle database returning JSON data.
TestWebService.asmx/getUserData
I test this using simply ajax request with jQuery
$.ajax({
type:"POST",
data:"{}",
dataType:"json",
contentType:"application/json; charset=utf-8",
url:"TestWebService.asmx/getUserData",
success:function(data){
console.log(data.d);
}
});
This work.
But now i want to try use Backbone.js
The Application have this: User data, Articles and Buy Order where a Buy order is a collection of Articles, so i think in this models for Backbone
User = Backbone.Model.extend({})
Article = Backbone.Model.extend({})
ArticleCollection = Backbone.Collection.extend({})
BuyOrder = Backbone.Model.extend({})
BuyOrderCollection = Backbone.Collection.extend({})
The Views are just 2. A Form where i show the User Data and inputs to add Articles and create the Buy Order and a Visualize view to show the Buy Orders where the user can see an check the content of one buy order clicking in the code.
The UserData, and part of the Article Data are get from the service: (User Data like name and Article Data like code, description, price, etc).
¿How can i populate the Backbone models with this data?
Thanks in advance.
So, basically, you want to override Backbone.sync. It is the thing that is currently doing your RESTful stuff (GET/POST/PUT/DELETE) via the $.ajax function as well. See how it is implemented by default: http://documentcloud.github.com/backbone/docs/backbone.html#section-134
As you can tell, it is really quite simple... about 30 or so lines of code to map create/update/delete/read to post/put/delete/get in $.ajax.
Now that you have seen how they do it, you just implement your own using the same pattern:
Backbone.sync = function(method, model, options) {
// your implementation
};
Once you do that, you are golden. Your models will do all the CRUD that you want them to, abstracted through your implementation of Backbone.sync.

Categories