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

Roudy Antenor
Roudy Antenor
4,124 Points

I've appended a new <div> with a button in to my DOM after an AJAX and transition -BUT i cannot get the button to work??

Hello everyone - i successfully made an AJAX call and placed the data in a <div>(along with a button) and appended it to a larger DIV container - Now i wish to take control of the button just created to do something else - IT's not registering - Yes it was added later to the DOM after the AJAX call but can't i still be able to use it?

function makeAjaxCall(){
    let userQuery = $('#welcomeBox input[type = "text"]').val();
       $.getJSON(
           `http://api.openweathermap.org/data/2.5/weather?zip=${userQuery},us&APPID=4b17ebXXXXXXXXXXXXXXXXXXX&units=imperial`,
          function(data) {
    let iconCode = data.weather[0].icon
    let iconUrl = `http://openweathermap.org/img/w/${iconCode}.png`;
    let temp = data.main.temp;
    let weatherDescription = data.weather[0].description;
    let cityName = data.name;

    let leftDiv = 
    `<div class="leftDiv appear">
        <img src="${iconUrl}" width="80" height="auto">
        <h2>${cityName}<h2/>
        <p>${new Date().toDateString()}</p>
        <p>${temp}</p>
        <p>${weatherDescription}</p>
        <p class="weatherDetails">Humidity: ${data.main.humidity}</p>
        <button>life</button>
    </div>
    `;
        $box.prepend(leftDiv);
}
       ) // end other half of  $.getJSON( ...
    } // end makeAjaxCall()

$('leftDiv button').on('click', function() {
    console.log('next');
})

The last 3 lines where i try to check if i can use the button nothing is logged when i click it - as if it still does not exist yet? Any help would be greatly appreciated.

1 Answer

Christof Baumgartner
Christof Baumgartner
20,864 Points

This is a tricky one indeed. AJAX is asynchronous, so other code can run, even when the AJAX-call is not ready. Instead you have to place you code, that should run afterwards, in the callback of the function. Disclaimer: I didn't test the code, but it should work:

function makeAjaxCall(){
    let userQuery = $('#welcomeBox input[type = "text"]').val();
       $.getJSON(
           `http://api.openweathermap.org/data/2.5/weather?zip=${userQuery},us&APPID=4b17ebXXXXXXXXXXXXXXXXXXX&units=imperial`,
          function(data) {
    let iconCode = data.weather[0].icon
    let iconUrl = `http://openweathermap.org/img/w/${iconCode}.png`;
    let temp = data.main.temp;
    let weatherDescription = data.weather[0].description;
    let cityName = data.name;

    let leftDiv = 
    `<div class="leftDiv appear">
        <img src="${iconUrl}" width="80" height="auto">
        <h2>${cityName}<h2/>
        <p>${new Date().toDateString()}</p>
        <p>${temp}</p>
        <p>${weatherDescription}</p>
        <p class="weatherDetails">Humidity: ${data.main.humidity}</p>
        <button>life</button>
    </div>
    `;
        $box.prepend(leftDiv);
        $('leftDiv button').on('click', function() {
             console.log('next');
        })
}
       ) // end other half of  $.getJSON( ...
    } // end makeAjaxCall()

Alternatively, you can use async false for AJAX request. Here is explained how: https://stackoverflow.com/questions/2765411/is-it-possible-to-set-asyncfalse-to-getjson-call