C
C
cyberlain2017-04-13 06:06:46
JavaScript
cyberlain, 2017-04-13 06:06:46

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

2 answer(s)
S
Sergey Sokolov, 2017-04-13
@cyberlain

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);

fiddle

A
Aleksandr Salamatov, 2017-04-13
@ch1sel

<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 question

Ask a Question

731 491 924 answers to any question