Dom problem in AJAX request

I have been stuck with this issue for almost 2 days, consider the following code:

'. country-select 'occurs twice in the form (input),

$('.branch-row').hide();
$('.country-select').change(function(){
    console.log($(this));
    country_select = $(this);
    $.get('get_country_branches.php',
        'country=' + $("'#" + country_select.attr('id') + " option:selected'").val() + '&field=' + $(':input:eq('+($(":input").index(country_select) + 1) +')').attr('name'),
        function(html){
            $(':input:eq('+($(":input").index(country_select) + 1) +')').html(html);
            //debug 1
            console.log(country_select);
            country_select.parent().parent().next().show();
        },
        'html'
    );

}).change();
//debug 2
console.log(country_select);

      

the output from debug 1 is the same object:

[select # pays-dem.country-select] [select # pays-dem.country-select]

however the output from debug 2 is correct:

[select # Pays-enlev.country-select] [Select # pays-dem.country-select]

The problem seems to be with the $ .get () AJAX function and the country_select object. Any wtf idea continues?

0


a source to share


3 answers


By not putting var in front of the country_select variable, it is bound to the global space, not the local function. Also, I don't think you need to query to get the selected value of the select. Use val()

should be enough. I would try to simplify the selection of what I think is the next entry after selection. Try something like this:

$('.country-select').change(function(){
    console.log($(this));
    var country_select = $(this);
    $.get('get_country_branches.php',
        'country=' + country_select.val() + '&field=' + country_select.next('input:first').attr('name'),
        function(html){
            country_select.next('input:first').html(html);
            //debug 1
            console.log(country_select);
            country_select.parent().parent().next().show();
        },
        'html'
    );

}).change();

      



By the way, this will break the console.log after the function, since the variable is no longer in the global scope.

+1


a source


You need to put var in front of country_select to make it a local variable. It is currently being defined globally.



Once you have done this, you will not be able to execute the second console.log as the variable will not be available at that point.

0


a source


Just wanted to add some details to my answer above.

Whenever you use a variable in JavaScript without declaring it in the function scope (using the var keyword), it is added to the global window scope.

So the following will be true

function myFunction(){
i=99;
if(i==99 && window.i == i){
alert("It went into global scope");
}
} 

myFunction();
if(i==99 && window.i == i){
alert("Same here");
}

      

0


a source







All Articles