I am writing a small code with JavaScript (using jQuery and Knockout) and HTML that takes user input (GitHub username), checks if the input is valid against a GitHub api, and displays the user's GitHub avatar and username (linked to the matching profile on GitHub). The display replaces the form in which the user entered the username.
The original HTML before the user inputs is:
<div id="inputSection">
<form>
<p>
GitHub Username:
<input type="text" name="username" value="" placeholder="username" id="un"/>
<button type="button" id="submitButton">Login</button>
</p>
</form>
</div>
And the code to replace it is this:
$("#submitButton").click(function() {
var username = document.getElementById('un').value;
var inputForm = $(document.getElementById('inputSection'));
$.ajax( {
...
success: function () {
alert("Welcome, " + username);
var userURL = 'https://github.com/' + username;
var inputContent = $('<a data-bind="attr: {href: userURL}"><img data-bind="attr: {src: avatar_url}" height="30" width="30"/>' + username + '</a>');
$(inputForm.replaceWith(inputContent));
}
});
});
It seems to work for the most part. After the alert welcomes the user by username, the form disappears from the webpage. It is replaced by the username, which is formatted like a link. However, it does not function as one. Clicking it does not do anything. Also, the user's avatar, despite showing a box of the set size on the webpage, does not appear.
The solution is likely very simple and obvious, but as I only started learning these languages and libraries this week, I am not sure what is going wrong. Knockout should be running on the HTML page that calls the JavaScript page, and the ajax is working with regards to other functions, so I assume that's fine. The value "avatar_url" is a part of the api requested with ajax at https://api.github.com/users.
I've tried all sorts of different things to no effect. If you want any more information or have a suggestion to make this question better, please comment. I'm new to coding and Stack Overflow, but I want to make both my programs and my questions as good as possible. Thank you for your time.
EDIT: 1. I originally failed to set a size for the image, resulting in a 0x0 image. This has been corrected, though the image itself still does not display. 2. When I first put in my code, I tried to make it easier to read by excluding where some variables had been renamed for other, unrelated portions and just making all the names match between the two relevant snippets. I did not catch them all. They should all match now.
Aucun commentaire:
Enregistrer un commentaire