Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Neil Bircumshaw
seal-mask
.a{fill-rule:evenodd;}techdegree
Neil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 Points

Coursework 5 - AJAX request

Hi, I'm trying to get two piece's of info when a pokemon name is typed into the text field, their name and their height. Just trying to keep things simple for now. I'm using the http://www.pokeapi.co/ API to do this. So far my JS code looks like this, I'm having a bit of difficulty getting it to work, went over the videos a few times but finding it difficult to wrap my head around AJAX. Perhaps the key that I've typed in is wrong or maybe I'm just way off with things! Any help will be great :)

JS

$("form").submit(function (evt) {
evt.preventDefault();
var $searchField = $("#search");
var pokeAPI = "http://pokeapi.co/api/v2/"   
var pokemon = $searchField.val();
var pokeInfo = {
    name:pokemon
    };

$.getJSON(pokeAPI,pokeInfo,displayInfo);

function displayInfo(data) {
var infoHTML = "<ul>";
$.each(data,function(i,data){
infoHTML += "<li>";
infoHTML += "<div class='album-wrap'>";
infoHTML += data.name + data.height;
infoHTML += "</div>"
infoHTML += "</li>"

});

infoHTML += "</ul>";
$("#main-content").html(infoHTML);
}

2 Answers

Seth Kroger
Seth Kroger
56,413 Points

It's a little hard to tell with the lack of indentation but if you check the DevTools console there is probably a syntax error from not closing off the submit function.

Neil Bircumshaw
seal-mask
.a{fill-rule:evenodd;}techdegree
Neil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 Points

Figured it out and made it super simple, it now returns the pokemon's name, average height and a picture of the pokemon! pretty neat :) Here's the code if anyone else is struggling.

$("form").submit(function (evt){
evt.preventDefault();
var $searchField = $("#search");
var pokemon = $searchField.val();
var pokeAPI = "http://pokeapi.co/api/v2/pokemon/" + pokemon     



function displayInfo(datas) {


var infoHTML = "<div class='album-wrap pokeCard'>" + "Pokemon name:  " + datas.name + "<br>" + "Average weight:  " + datas.weight/10 + "  kg" + '<img class = "pokeimg" src="' + datas.sprites.front_default + '"alt="Pokemon" height="200" width="200">'  + "</div>";



$(".main-content").html(infoHTML);
}

$.getJSON(pokeAPI,displayInfo); 

})