Showing posts with label Javascript/Jquery. Show all posts
Showing posts with label Javascript/Jquery. Show all posts

How to get custom user profile property from SharePoint User Profile Service using JavaScript AJAX client side script

Hi There,

SharePoint provides a wonderful facility of client side scripts to get data from SharePoint objects. You can get custom user profile property from SharePoint User Profile Service using JavaScript AJAX calls. Below is an example.

I have an AD property with name "Initials" that do not comes in SharePoint OOTB  User Profile Service and you have to bind it manually.

I have set its internal name also "Initials" in my User Profile Service while binding it. We'll call this property using the same name. Remember that, you can only call a User Profile Property from its internal name.


I have bonded it with "Initials" attribute of AD and set the Direction to Import. Click Add.



Now the custom property is appearing when i edit any user profile.


Below is my JavaScript code.

[code]//Display User profile properties function getMyUserProfile(success, error) { var siteUrl = _spPageContextInfo.siteAbsoluteUrl; //You can replace this with your site URL too. i.e http://anysite.com $.ajax({ url: siteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function (data) { var json = $.parseJSON(JSON.stringify(data.d)); alert("Hello " + json.DisplayName + " Your Job Title Is : " + json.Title + " Profile Picture URL is :"+ json.PictureUrl + " MySite URL is :"+ json.PersonalUrl); for (var i = 0; i < data.d.UserProfileProperties.results.length; i++) { if (data.d.UserProfileProperties.results[i].Key == "Initials") { alert("Your Custom Property Initials is : " + data.d.UserProfileProperties.results[i].Value); } } }, error: error }); } // Usage getMyUserProfile(function (properties) {}, function (data) { console.log(JSON.stringify(data)); }); [/code]
Boom...! It worked for me.

You can check some suggested codes here too which worked fine and provide another way to use the same code. I am also posting that samples below.

Sample 1:

[code]SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');

    var userProfileProperties;

    function getUserProperties() {
    var clientContext = new SP.ClientContext.get_current();
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    userProfileProperties = peopleManager.getMyProperties();
    clientContext.load(userProfileProperties);
    clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
    }
    function onRequestSuccess() {
    var Bild = userProfileProperties.get_userProfileProperties()['PictureURL']
    document.getElementById("div").innerHTML = userProfileProperties.get_userProfileProperties()['WorkEmail'];
    document.getElementById("div1").innerHTML = userProfileProperties.get_userProfileProperties()['PreferredName'];
    document.getElementById("div2").innerHTML = userProfileProperties.get_userProfileProperties()['WorkPhone'];
    $("#bild").attr('src', Bild);
    }

    function onRequestFail(sender, args) { alert( args.get_message());}[/code]

Sample 2:

[code]<script type="text/javascript">


    var workEmail = "";
    var EmployeeID = "";
    var Division = "";
    var userDisplayName = "";
    var AccountName = "";

    $.ajax({

        url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
        headers: { Accept: "application/json;odata=verbose" },
        success: function (data) {
            try {
                //Get properties from user profile Json response
                userDisplayName = data.d.DisplayName;
                AccountName = data.d.AccountName;
                var properties = data.d.UserProfileProperties.results;
                for (var i = 0; i < properties.length; i++) {

                    if (property.Key == "WorkEmail") {
                        workEmail = property.Value;
                    }

                    if (property.Key == "EmployeeID") {
                        EmployeeID = property.Value;
                    }
                    if (property.Key == "Division") {
                        Division = property.Value;
                    }

                }
                $('#AccountName').text(AccountName);
                $('#userDisplayName').text(userDisplayName);
                $('#EmployeeID').text(EmployeeID);
                $('#workEmail').text(workEmail);
                $('#Division').text(Division);


            } catch (err2) {
                //alert(JSON.stringify(err2));
            }
        },
        error: function (jQxhr, errorCode, errorThrown) {
            alert(errorThrown);
        }
    });

</script>

<br />
<h2>
<strong>Employee Details</strong></h2>
<br />
AccountName   <span id="AccountName"></span>
DisplayName   <span id="userDisplayName"></span>
EmployeeID    <span id="EmployeeID"></span>
Email Address <span id="workEmail"></span>
Division      <span id="Division"></span></div>[/code]
How to find city weather dynamically from Google map and Yahoo weather API with JavaScript

How to find city weather dynamically from Google map and Yahoo weather API with JavaScript

Hi There,


If you have read my post How to get city weather from Yahoo Weather API using Javascript and How to get city name against google map latitude and longitude using javascript then it would be probably more easy for you to get the required stuff.

We'll get city name from Google Map GeoLocation and weather status from Yahoo Weather JavaScript API call. Below is sample example code for this combined. You can Google around to get more information about these API's.

JavaScript Code:

[code]var Wcity;// = "Gilgit"; var yahooWeatherAPI; var GoogleAPI; $(document).ready(function () { GetLocation(); }); function GetLocation() { navigator.geolocation.watchPosition(callback); } function callback(position) { GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&key=AIzaSyAswpJn5_eL3fmsnFocNmiSsgXVog3CsH8"; //Fetching City Name $.getJSON(GoogleAPI, function (json) { if (Wcity == undefined) { Wcity = json.results[0].address_components[3].short_name; //alert(json.results[0].formatted_address); } ///Fetching Weather Report yahooWeatherAPI = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + Wcity + "%2C%20PK%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"; $.getJSON(yahooWeatherAPI, function (json) { var temp = Math.round((((json.query.results.channel.item.condition.temp - 32) * 5) / 9));// + "°"; $('#currentWeather').text(temp); $('#weatherCity').text(Wcity); }); } });[/code]

HTML Code:

[code][/code]

Happy Coding :) 
How to get city name against google map latitude and longitude using javascript

How to get city name against google map latitude and longitude using javascript

Hi There,

Before moving ahead please make sure you have a valid Google API key otherwise after few hits to google service it will throw a daily limit exceed exception in your ajax call. You need a Server API Key for this not Browser API Key from Google.

You need to include below references in your HTML code first.

[code][/code]

JavaScript Code:

[code]function GetLocation() { navigator.geolocation.watchPosition(callback); } function callback(position) { GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," + position.coords.longitude + "&key=YOUR API KEY HERE"; //Fetching City Name $.getJSON(GoogleAPI, function (json) { if (Wcity == undefined) { Wcity = json.results[0].address_components[3].short_name; alert(Wcity); } }[/code]

Please note that, in most of the cases Google map throws city name on ".address_components[3]" however you can change it to index ".address_components[2]" as well and trick with the results.

Happy Coding :)
How to get city weather from Yahoo Weather API using Javascript

How to get city weather from Yahoo Weather API using Javascript

Hi There,

Yahoo provides a superb JavaScript API to get weather updates for a specific city. More you can read Yahoo weather API documentation on Yahoo official website. However i am putting here a sample JavaScript code that how you can get city weather from Yahoo weather dynamically.

JavaScript Code:

[code]var Wcity = "Gilgit"; ///Fetching Weather Report yahooWeatherAPI = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + Wcity + "%2C%20PK%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"; $.getJSON(yahooWeatherAPI, function (json) { var temp = Math.round((((json.query.results.channel.item.condition.temp - 32) * 5) / 9));// + "°"; $('#currentWeather').text(temp); $('#weatherCity').text(Wcity); }); [/code]

HTML Code:

[code][/code]

Try replacing the city with your desired city name or get the city name dynamically and use this ajax call in your function. It worked for me and hope work for you as well.

Please notice that in yahooWeatherAPI url above, i have highlighted PK as its the country code word for yahoo. You may have to change it according to your country. I am currently in Pakistan so it works fine for me.

Happy Coding :)
How to show "Loading..." in Jquery Ajax Call

How to show "Loading..." in Jquery Ajax Call

Hi There,

Well, that's pretty simple now. Below is the sample code that you can customize according to your needs. It will show a smooth Loading... with jquery effect.

JQuery Code:

            $("#loading").fadeIn("slow");
$.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://localhost:8080/Service.asmx/GetEmployessJSON",
data: { UserName: GetUserName(), Month: Month, Year: Year }, // example of parameter being passed
dataType: "jsonp",
success: onDataReceived
});

function onDataReceived(data) {
$("#loading").fadeOut();
$("#myDiv").text(data.MyCustomProperty);
}

HTML Code:

        <div id="loading" style="display: none;">
Loading....
</div>


Happy Coding :)
How to consume cross site asmx returned Json service with Javascript

How to consume cross site asmx returned Json service with Javascript

Hi There,

If you are trying to access a web service which is hosted on other domain or port or outside the network, you need to use jsonp instead of json. After spending hours, finally i found a solution on stackoverflow ( the only friend site of developers :o)  Thanks to NickG for writing this answer). You can read the inside story of this issue on the actual question on stackoverflow. I am posting here the direct code which worked for me. Hope you get some clue from here.

Javascript / Jquery Code:

        $.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://localhost:8080/Service.asmx/MyCustomMethodName",
data: { User: 'Admin', Mon: 8}, // example of parameter being passed
dataType: "jsonp",
success: onDataReceived
});

function onDataReceived(data) {
alert("Hi " + data.UserName + " Its " + data.Month + " of this year.");
}


C# Employee Class:

    public class Employee
{
public string UserName { get; set; }
public int Month { get; set; }

}


Service.asmx Class:

 /// <summary>
/// Summary description for Service
/// </summary>
[WebService(Namespace = "http://contoso.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ScriptService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void MyCustomMethodName(string User, int Mon, string callback)
{
Employee emp = new Employee();
emp.UserName = User;
emp.Month = Mon;
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(emp));
sb.Append(");");

Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
}

As described in this article, the "string callback" in the above method is the default query string parameter that Jquery passes itself. If you want to see what is passing in it, use chrome, press F12 and see in request headers. This example worked for me perfectly.

Hope it helps someone.