0

I am making an AJAX call in my script which grabs HTML from the server. I need to replace my existing HTML with the returned data. The replacement works, but the variables lose their context, meaning I cannot fire the function to replace again.

This is what my JavaScript looks like:

(function($){

    var $weatherCard = $(".weather-card");
    var $reloadWeather = $(".reload-weather");
    var $newLocation = $("#zip").val();
    var $featureParent = $(".pb-f-global-weather-forecast");

    $reloadWeather.on('click', function() {
        var $newLocation = $("#zip").val();
        changeLocation($newLocation);
    });

    function changeLocation(location) {

            $.ajax({
            "url" : $reloadWeather.data('path') + '?' +
                'contentConfig={\"Type\":\"forecast\",' +
                    '\"City\":\"' + location + '\",' +
                    '\"Country\":\"USA\",' +
                    '\"Count\":\"5\"' + '}',
                //'&customFields={\"enabledLoadMore\":true,' + '"layoutMode":' + '"' + $loadMoreButton.data('feed-layout') + '"' + ',' + '"dateType":' + '"' + $loadMoreButton.data('date-type') + '"' + ',' +  '"hideSubhead":' + '"' + $loadMoreButton.data('show-sub') + '",' + '"hideDate":' + '"' + $loadMoreButton.data('show-date') + '",' + '"hideByline":' + '"' + $loadMoreButton.data('show-byline') + '"' + '}',
            "timeout" : "1500",
            "method": "GET",
            "accept" : false
        }).done(function(data) {
            $featureParent.replaceWith(data.rendering);
        });
    };

In other words I want the variables listed at the top to be re-assigned to the same element once the replaceWith() function is fired. Re-assigning the variables within the done function doesn't seem to work.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
James Ives
  • 3,177
  • 3
  • 30
  • 63
  • 2
    Reassigning the variables in the done function should definitely work. You also need to rebind the event handlers. But maybe you should use event delegation, see http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Barmar Sep 30 '16 at 17:43
  • `var $weatherCard = $(".weather-card");` only creates collection of elements that exist at the time it is run. Even if you replace with exact same html ... it's not same dom object reference – charlietfl Sep 30 '16 at 17:51

0 Answers0