skip to Main Content

I’m looking to retrieve a user’s avatar using their user name, retrieve it in an input field. However what I did does not work and I am not familiar with Ajax. Could someone help me and explain the procedure to me?

<input type="text" name="username" class="input" placeholder="Your username">
<img id="#result" src=""></img>

Here is my ajax

$(document).keyup(function (event) {
    $.ajax({
        url: "App/Actions/PlayerGetFigure.php",
        type: "post",
        data: {
            login: function () {
                return $(':input[name="username"]').val();
            },
        },
        success: function (data) {
            $('#result').html(data);
        }
    });
});

And here is my PHP

require '../../vendor/autoload.php';

use AppModelsUsersManager as Users;

$Users = new Users();

$username = $_POST['username'];

if (isset($username)) {
    $user = $Users->getByUsername($username);
    if ($user) {
        echo $user['avatar'];
    } else {
        return false;
    }
}

2

Answers


  1. If this is your HTML:

    <input type="text" name="username" class="input" placeholder="Your username">
    <img id="result" src=""></img>
    

    I would advise the following jQuery.

    $(function(){
      function getAvatar(username){
        var url = "";
        $.post("App/Actions/PlayerGetFigure.php", { login: username }, function(data){
          url = data;
        });
        return url;
      }
      $("input[type='username']").change(function(){
        $("#result").attr("src", getAvatar($(this).val()));
      });
    });
    

    This assumes that the PHP Script will return a (Relative or Absolute) URL Path to the Image.

    Login or Signup to reply.
  2. I would personally take this approach, it looks a bit cleaner for me (assuming that $user['avatar'] returns the path to the image)

    HTML

    <input type="text" id="username" class="input" placeholder="Your username" />
    <div id="result"></div>
    

    AJAX

    $(document).keyup(function (event) {
        let username = $('#username').val();
        $.ajax({
            url: "App/Actions/PlayerGetFigure.php",
            type: "post",
            data: { login:username },
            success: function (data) {
                $('#result').html(data);
            }
        });
    });
    

    PHP

    require '../../vendor/autoload.php';
    
    use AppModelsUsersManager as Users;
    
    $Users = new Users();
    
    $username = $_POST['username'];
    
    if (isset($username)) {
        $user = $Users->getByUsername($username);
        if ($user) {
            $avatar = $user['avatar'];
            echo "<img src='$avatar'></img>";
        } else {
            return false;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search