在Ajax内部触发成功

I want to trigger function only when Ajax success

my function ajax

$.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        success: function(msg) {
            console.dir(msg);    
            if(msg.status == 'OK'){
                $("#fb-root").on("facebook:init", function(event, response) {
                   if(response.status === 'connected') {
                      alert("LOG")
                   }else{
                      alert(" NO LOG ");
                   }
                });
          }
        }
    });

Trigger Function

function getLoginStatus() {
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            $('#fb-root').trigger('facebook:init',[response]);

        } else if (response.status === 'not_authorized') {
            $('#fb-root').trigger('facebook:init',[response]);
        } else {
            $('#fb-root').trigger('facebook:init',[response]);
        }
    });
}

Never alert("LOG") or alert("NO LOG");

if i use

$("#fb-root").on("facebook:init", function(event, response) {
    if(response.status === 'connected') {
        alert("LOG")
    }else{
        alert(" NO LOG ");
    }
});

outside ajax, it's works

Thanks

I think you need this:

    //Move this function outside ajax as this is to register event handler, not to trigger the function.
    $("#fb-root").on("facebook:init", function(event, response) {
        if(response.status === 'connected') {
            alert("LOG")
        }else{
            alert(" NO LOG ");
        }
    });

    function getLoginStatus() {
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                $('#fb-root').trigger('facebook:init',[response]);

            } else if (response.status === 'not_authorized') {
                $('#fb-root').trigger('facebook:init',[response]);
            } else {
                $('#fb-root').trigger('facebook:init',[response]);
            }
        });
    }

 $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        success: function(msg) {
            console.dir(msg);    
            if(msg.status == 'OK'){
                 getLoginStatus(); //only trigger the function when ajax is successful.
               //or  $('#fb-root').trigger('facebook:init',msg);
            }
        }
    });

$("#fb-root").on("facebook:init" is to register event handler, not to trigger event. You should always add the event handler outside $.ajax function and trigger it to fire inside your success function.