Variable does not have its value after done or fail in ajax [duplicate]

1

I created a function to return true or false when ajax. At the beginning of the function I declare a variable "r" to receive true in case of success or false in case of failure, but the variable does not have its value modified. and ends up returning the value that was assigned at start false . What's wrong?

function loadSkeleton(r) {
    var r;
    $.ajax({
        method: "POST",
        url: "/sys/ajax/publicacao.xhtml"
    }).done(function (answer) {
        $('head').append('<link rel="stylesheet" type="text/css" href="/css/post.css">');
        $('head').append('<link rel="stylesheet" type="text/css" href="/css/aside-publication.css">');
        $('head').append('<script type="text/javascript" src="/scripts/js/other-publi.js"></script>');
        setTimeout(function () {
            $('.side-left').html($(answer).find('content').html());
        }, 2000);
        r = true;
    }).fail(function (jqXHR, textStatus) {
        $('.side-left').html('<p>Failed request</p>');
        r = false;
    });
    return r;
}

.done is working because DOM changes are visible.

    
asked by anonymous 19.01.2017 / 03:49

1 answer

2

Good evening. What is happening is that the function you created is immediately returning the value of r , and the .done and .fail methods are assíncronos , that is, they get functions as a parameter (in this case, you are two anonymous functions) that are invoked later (when the request is successfully completed or when an error occurs).

To try to adapt your function to the purpose you want (receive true or false, depending on the success of the request), you can send a function as an argument and invoke it as needed. Something like this:

function loadSkeleton(fnOK) {
    $.ajax({
        /* ... */
    }).done(function (answer) {
        /* ... */
        fnOK(true);
    }).fail(function (jqXHR, textStatus) {
        /* ... */
        fnOK(false);
    });
}

/* 
    Quando você for chamar a função loadSkeleton, passe como argumento
    uma função (neste caso aqui, uma função anônima)
*/

loadSkeleton(function(ok) {

    /*
        O parâmetro será true, ou false, 
        dependendo de como ela for invocada lá no loadSkeleton.
    */
    console.log(ok); 

});

/* 
   Ou declare sua função - callback antes e passe como argumento 
   Obs.: sem os parêntese, apenas a referência - parênteses iria invocá-la, 
   que não é o que queremos

*/

var fnOK = function(ok) {
    console.log(ok); 
};

loadSkeleton(fnOK);

I suggest reading this answer here on SOPt on callbacks and this chapter on Top Order Functions / High Order Functions

    
19.01.2017 / 04:25