Answer the question
In order to leave comments, you need to log in
How to get a photo of a VKontakte user by his id (using js)?
Actually, we need an example of a function that takes the user id and returns the src of his ava
Answer the question
In order to leave comments, you need to log in
You need to call the VKontakte API users.get() method - it returns information about the user, incl. his avatars. Because the request is made from JavaScript from your site's domain to another domain api.vk.com
, this is a cross- domain request . In jQuery ajax, you need to specify the data type jsonp
.
The request will be asynchronous, so we pass the VK user id and the callback function to the function, which will be called when we receive a response from VK with a link to the image:
function getPhoto( id, callback) {
$.post({
url: "https://api.vk.com/method/users.get",
data: {
user_id: parseInt(id),
fields: "photo_100",
v: 5.63
},
dataType: "jsonp",
success: function(r) {
if(r && r.response && r.response[0].photo_100) {
return callback(r.response[0].photo_100);
} else {
console.log("No photo in response")
}
}
});
}
function gotPhoto( url) {
var img = $('<img>')
.attr('width', 100)
.attr('height', 100)
.attr('src', url)
;
$('body').append(img);
}
getPhoto( 755074, gotPhoto);
<body>
<img id="ava" />
</body>
<script>
function getAva(user_id) {
$.ajax({
url: 'https://api.vk.com/method/users.get?user_ids=' + user_id + '&fields=photo_max_orig',
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
var ava = data.response[0].photo_max_orig;
document.getElementById("ava").setAttribute("src", ava);
}
});
}
getAva("ch1seL");
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question