Chiptus
Chiptus

Reputation: 951

calling a function on the first time won't work as expected, but next time is working

here's my code:

treksID=[];
recommendedTrekId=2;

$(document).ready(function(){
    showTrek('random');
    showTrek(recommendedTrekId);
});

function showTrek(filter){
    if (filter=="random"){
        param={action:'getShortTrek'};
        tagId="#random";
        index=1;
    }
    else {
        param={action:'getShortTrek', Trek_Id:filter};
        tagId="#recommend";
        index=0;
    }
    $.getJSON('php/treks.php',
        param,
        function(data){
            $(tagId).find('h3').html(data[0].Trek_Name);//PROBLEM
            treksID[index]=data[0].Trek_Id;//PROBLEM
            if (filter=='random') {alert('debug'); test=data;}//DEBUG
        }
    );
}   

On the first time showTrek is called it does everything as expected but not the two problematic lines (marked with //PROBLEM tags) the second time does work. also after that when I call showTrek('random'); in the browser console it does work. what is strange is that data does contain the right object (checked by viewing test).

I'm feeling a bit crazy when programming does that, can anyone see my problem?

Upvotes: 1

Views: 1582

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382170

That's because you declared your variables param, tagId and index as global by forgetting the var keyword. This makes their first values erased by the second call to showTrek and this call happens before the first callback you pass to $.getJSON is executed because the AJAX call is asynchronous.

You should simply add

var param, tagId, index;

at the start of the showTrek function.

Upvotes: 6

Related Questions