Pregunta

I'm getting undefined results from a .each called upon after a .post. The following is my code.

Javascript

    var index=0;
    $("td.load_ads").each(function(){
        var loading=$(this);
        $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id'},function(data){
            if($("input.exist").length > 0){
                $("input.exist").each(function(){
                    if($(this).val()==data){
                        var load='0';
                    }else{
                        var load='1';
                    }
                });
            }else{
                var load='1';
            }
            alert(load);
            if(load == 1){
                $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_details',id:data},function(data2){
                    $("body").append('<input type="hidden" class="exist" name="exist" value="'+data+'">');
                    if(data2!=0){
                        loading.html(load+'--'+data2);
                    }else{
                        loading.html("Place a Free Ad Now!");
                    }
                });
            }else{
                loading.html(load+"--"+data+"Place a Free Ad Now!");
            }
        });
        index=index+1;
    });

What I'm trying to do here is launch a .post on each of my td.load_ads, after which check the data with each existing input.val. If the input value on each of this existing inputs is the same as the data collected, then i will not echo out the second .post results.

However, the whole operation doesn't seem to show correctly. I realise my problem is at the .each after the .post. When i did my alert(load). The results returned were undefined. Am i missing out something or is it that my coding is logically incorrect? Any help will be greatly appreciated.

/*Added Problem/*

So now, I've another problem so I thought might as well just add it here.

I try appending the inputs

($("body").append('');)

in the second section of the script.

So that when the loop repeats itself, it will be able to read the input and take in the newly appended inputted values. But my load always returns 1 because my $("input.exist").length always returns false.

Or is this not possible to do with jquery?

/*END OF ADDED PROBLEM/*

¿Fue útil?

Solución

You need to declare the load variable ahead of time. Right now, you are declaring it twice inside of an anonymous function, and the variable's scope will be limited to that function; the var load = ...; statements will have no observable effect from the perspective of the outer function.

Try this instead:

var load = '1';

if($("input.exist").length > 0){
    $("input.exist").each(function(){
        if($(this).val()==data){
            load='0';
        }else{
            load='1';
        }
    });
}

alert(load);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top