0

I try to pass a var that I get from an ajax request on focusout to the next mouseover function.

But the var that I define in the first focusout function is not accessible/undefined in the second mouseover funtion. Is there a clean simple way to do that?

here is the jsfiddle example

    $(document).ready(function() {  
    var mc;

        $('#login').on('focusout', function() {
            var mc = $('#login').val();
            alert(mc)
        });

        $("#submit").on('mouseover', function() {
            alert(mc)   
        });
    });

and here is my original code with the ajax request

$(document).ready(function ($) {
    var access_key = '123456';
    var mc;

    $('#userLoginName').on('focusout', function () {
        var email = $('#userLoginName').val()
        // verify email address via AJAX call
        $.ajax({
            url: 'https://ajaxrequesturl.de/check?key=' + access_key + '&email=' + email,
            dataType: 'jsonp',
            success: function (json) {

                // Access and use your preferred validation result objects
                console.log(json.format_valid);
                console.log(json.smtp_check);
                console.log(json.score);
                var mc = json.smtp_check;
                //alert(json.smtp_check);
                //alert(mc);    
            }
        });
    });

    $(".nextstep-inner").on('mouseover', function () {
        if (mc) {
            $(".isa_error").hide();
        } else {
            $(".isa_error").show();
        }
        alert(mc);
    });
});
baj9032
  • 2,414
  • 3
  • 22
  • 40
Kuba
  • 189
  • 3
  • 23

1 Answers1

0

In the $('#login').on('focusout', ...) function you are creating a new mc variable local to that function, which is shadowing the other variable defined outside.

Replace:

    $('#login').on('focusout', function() {
        var mc = $('#login').val();
        alert(mc)
    });

with:

    $('#login').on('focusout', function() {
        mc = $('#login').val();
        alert(mc)
    });
Maluen
  • 1,753
  • 11
  • 16
  • 1
    This question already has an answer here: [Access variable outside function scope](https://stackoverflow.com/questions/16942043/access-variable-outside-function-scope) 1 answer – Muhammad Ashikuzzaman Nov 20 '17 at 10:29