Why does the .click function of jQuery update everything in the document in second click?

advertisements

I am using jQuery in my web site. Following is the code i am getting problem with:

 $("#activitiesbtn").click(function(){
    $('#dashboard-mainsubhead').load('activity.html', function() {
        // doing some stuff here

        // Following code is making problem
        $('.subareas').bind('click', function(){
            var keytext = $(this).find('.areakey').text();

            $.ajax({
                type: 'POST',
                url: 'http://localhost:8888/getactivity',
                data: {activitykey: keytext},
                success: function(result) {
                    activityobj = jQuery.parseJSON(result);
                }
            });

            var activityurl = activityobj.mapurl;
            var activmapurl = "<img src=\""+activityurl+"\"></img>";
            $('#activity-mapimg').html(activmapurl);
            $('#activity-activitykey').html(activityobj.key);
            $('#activity-activitymode').html(activityobj.activityMode);
            $('#activity-time').html(activityobj.totalTimeTaken);
            $('#activity-distance').html(activityobj.totalDistanceCovered);
            $('#activity-calories').html(activityobj.calories);
            $('#activity-wallutas').html(activityobj.wallutas);

            alert("subarea div clicked");
        });
    });
});

problem is that first time when i click any of div which has subareas class, nothing happens. But after that every time when i click any subareas class div, alert "subarea div clicked" comes but text of other divs changes on every second click. Why is it happening? Any idea? Thanks in advance.


First, you need to unbind the click every time otherwise the code will execute multiple times.

Second, you need to use the data returned by the .ajax call only in the success event:

$('.subareas').unbind("click");
$('.subareas').bind('click', function(){
    var keytext = $(this).find('.areakey').text();
    $.ajax({
        type: 'POST',
        url: 'http://localhost:8888/getactivity',
        data: {activitykey: keytext},
        success: function(result) {
            activityobj = jQuery.parseJSON(result);
            var activityurl = activityobj.mapurl;
            var activmapurl = "<img src=\""+activityurl+"\"></img>";
            $('#activity-mapimg').html(activmapurl);
            $('#activity-activitykey').html(activityobj.key);
            $('#activity-activitymode').html(activityobj.activityMode);
            $('#activity-time').html(activityobj.totalTimeTaken);
            $('#activity-distance').html(activityobj.totalDistanceCovered);
            $('#activity-calories').html(activityobj.calories);
            $('#activity-wallutas').html(activityobj.wallutas);
        }
    });
});

The variable activityobj won't have any value outside the $.ajax() function the first time it executes - the second time it has the value of the previous call.