0

I think i have not understood correctly var scalabality. Can you explain me this :

i have a function like that :

function myFunction () {
    var test = $(this).data('type');
    console.log("start :"+test);

    $.ajax({
        url: 'myUrl',
        type: 'POST',
        contentType: false,
        processData: false,
        dataType: 'json',
        data: data,
        success: function (response) {
            console.log("end :"+test);
        }
    });
}

This function is called when i click on a button :

$('.js-button').on('click', myFunction);

when i submit my form, i have to trigger the click on all visible buttons so i do :

$('.submit').click(function(){
    $('.button').each(function(){
        if ($(this).is(":visible")){
            $(this).trigger("click");
        }
    });

    return false;
});

in my function, "$(this).data('type')" gets the data-type atribute of the button

If i have 2 visible buttons with data-type="toto" and data-type="titi", i have this log :

start :toto
start :titi
end :titi
end :titi

Why do i have "titi" two times in the ajax callback i thougt "var test" was not global, am i wrong

thanks for your help

EDIT : here is a jsFiddle if "test" is declared without "var", you can reproduce if you write "var test = = $(this).data('type');" it works correctly

pop_up
  • 1,451
  • 2
  • 18
  • 35
  • 4
    *"Why do i have "titi" two times in the ajax callback"* You don't, in that code. You've shown several disconnected code blocks, making it hard to help you. Instead, do a single **runnable** [mcve] using Stack Snippets (the `<>` toolbar button) so we can see exactly what code you're running and exactly what it's doing. – T.J. Crowder Sep 15 '16 at 09:31
  • That said, you're probably running into [this problem](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – T.J. Crowder Sep 15 '16 at 09:32
  • 1
    [The code you've posted is working the way you expect it to and not the way you describe](https://jsfiddle.net/0fscxmdn/) – David Hedlund Sep 15 '16 at 09:34
  • I edited the post to add a testable code. Thanks for your help (and links) – pop_up Sep 16 '16 at 15:06

0 Answers0