1

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 App\Models\UsersManager as Users;

$Users = new Users();

$username = $_POST['username'];

if (isset($username)) {
    $user = $Users->getByUsername($username);
    if ($user) {
        echo $user['avatar'];
    } else {
        return false;
    }
}
  • What specifically goes wrong? – showdev Mar 31 '20 at 22:34
  • I have just understood the why of the how. I pass a $_POST method I must pass a $_GET method to be able to retrieve the information from my input field. – Benjamin Peuple Mar 31 '20 at 22:36
  • What specifically goes wrong? Does the AJAX work correctly? One issue is that [`` elements](https://html.spec.whatwg.org/multipage/embedded-content.html#the-img-element) have a ["nothing" content model](https://html.spec.whatwg.org/multipage/dom.html#concept-content-nothing) and can't hold any content; if `$user['avatar']` is an image URL, you may want to assign it to the `` element's [`src` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/src) instead of its value. See [Changing the image source using jQuery](https://stackoverflow.com/questions/554273/). – showdev Mar 31 '20 at 22:43
  • Finally I would like to recover the url of the image stored in the database and assign it to the element `` when I mark the nickname of a person. I had a PHP error is that it could not find `$ _POST['username']` because I did not validate my form. I just had to pass my "username" value through a `$_GET` method – Benjamin Peuple Mar 31 '20 at 22:44
  • `$_POST` should work, since your AJAX request is set to `type: "post"`. See [jQuery.ajax()](https://api.jquery.com/jquery.ajax/): "*type*: An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0." However, you're accessing `$_POST['username']` when the value is posted under the "login" key: `data: { login:`. To see the posted values, you might try `echo "
    ".print_r($_POST,true)."
    ";`.
    – showdev Mar 31 '20 at 22:47
  • 1
    Okay, I just understood. However now I have another problem. I recover my image well in ajax but I can't change the source of my image when a user writes his nickname – Benjamin Peuple Mar 31 '20 at 22:51
  • 1
    Is the value of `$user['avatar']` an image URL? That's what I was saying earlier about [setting the `` src attribute](https://stackoverflow.com/questions/554273/changing-the-image-source-using-jquery). – showdev Mar 31 '20 at 22:55
  • Oh ok ! But how can I change the value of my with the response I receive in Ajax? – Benjamin Peuple Mar 31 '20 at 22:56
  • By assigning the value to the `` element's src attribute. Also see [JQuery change the value of an – showdev Mar 31 '20 at 22:58
  • I tried but it doesn't work with my code : `success: function (data) { $('#result').attr('src', data+'.jpg'); console.log(data); }` – Benjamin Peuple Mar 31 '20 at 23:02
  • What is the output of `console.log(data);`? Does it include the ".jpg" part already? – showdev Mar 31 '20 at 23:03
  • I have the data I expected, the url of my image. – Benjamin Peuple Mar 31 '20 at 23:04
  • Does it change the image `src` to something like `avatar.jpg.jpg`? Does it include the correct path to the image (e.g. `images/avatar.jpg`)? – showdev Mar 31 '20 at 23:10
  • Yes, insert the image is correct, it's my #result element which does not update the source of my image that I assign to it in the "success" function – Benjamin Peuple Mar 31 '20 at 23:11
  • 1
    Ah, the HTML says `id="#result"`. It should likely say `id="result"` (no hashtag). [Here's a demo](https://jsfiddle.net/m2e31scg/). – showdev Mar 31 '20 at 23:17
  • Ok I'm definitely stupid. thank you very much for your help, Everything works, my god, it was horrible but I can understand everything thanks to you !!! – Benjamin Peuple Mar 31 '20 at 23:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210701/discussion-between-benjamin-peuple-and-showdev). – Benjamin Peuple Mar 31 '20 at 23:23

2 Answers2

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.

Twisty
  • 23,484
  • 1
  • 22
  • 40
  • Thank you for your answer ! In fact I expected a response with the `$_GET` method because my goal was to update as soon as my input field is filled. So I went through a `$_GET` method and I manage to recover the data I wanted (the url of a user's avatar). However I can't update the avatar with my "success" function – Benjamin Peuple Mar 31 '20 at 23:07
  • @BenjaminPeuple that does not make sense wince your PHP Script is set for `$_POST` variable. – Twisty Mar 31 '20 at 23:09
  • Yes, I modified it, now I go through a variable `$_GET`. – Benjamin Peuple Mar 31 '20 at 23:10
  • And your code could not work, you pass a input type "username". But your solution helped me a lot ! I didn't know that the $.post() and $.get() methods existed in Jquery. – Benjamin Peuple Mar 31 '20 at 23:14
  • 1
    @BenjaminPeuple yes, they are shorthand for `$.ajax()` for the respective method. – Twisty Mar 31 '20 at 23:22
1

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 App\Models\UsersManager 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;
    }
}
Nyx
  • 314
  • 1
  • 13